How to override logger class in implicits?

i have an object which contains an implicit class

object implicits extends LazyLogging {
  implicit class StringOps(str: String) {
    def prettyPrint(): Unit = {
      val print: String = s"*** $str ***"
      val pretty: String = "*" * print.length
      List(pretty, print, pretty).foreach { str => }

When i use this implicit prettyPrint it prints logger class always as [package_name].implicits:

import implicits._
object Main extends App {
  "pretty".prettyPrint // logger class will be `implicits` instead of `Main`.

My question is how can i use this implicit prettyPrint with overriden logger class ?

Please ensure to provide all relevant information - in this case, the logging library used (scala-logging) would’ve been of interest.

You could materialize the logger at the call site and require it in implicit scope at the impl site.


// LoggerUtil.scala
trait LoggerUtil extends LazyLogging {
  implicit val defaultLogger: Logger = logger

// implicits.scala
object implicits {
  implicit class StringOps(str: String) {
    def prettyPrint()(implicit logger: Logger): Unit = ...

// Main.scala
object Main extends App with LoggerUtil {

(Contrast with log4cats, where logger naming and creation are decoupled: Logger factory methods accept an implicit LoggerName.)

1 Like

I applied your suggestion, please look at snapshot. It still prints logger class as implicits$StringOps

Caller class name (%C), file name (%F), line number (%L), etc., are probably extracted by the underlying log system (log4j2) via reflection on stack trace elements, and this will very likely always and unconditionally consider the parent frame of the logger invocation as the caller. I’m not aware that this level of information exists in slf4j at all, so there’s no (sane) way of tampering with it.

I’ve been talking about the logger name (%c), which by default is derived from the name of the class containing the code that creates the logger instance. This name is affected by shifting logger creation as suggested.

1 Like

Yeah, indeed. I wasn’t knowing about %c. Thank you a lot for letting me know.