简体   繁体   English

与Groovy @ Slf4j注释对应的Scala

[英]Scala equivalent for Groovy @Slf4j annotation

Migrating from Groovy to Scala here. 从Groovy迁移到Scala。 So far I really like Scala, however I am instantly missing my @Slf4j annotation, where I could just have: 到目前为止,我真的很喜欢Scala,但是我立即就错过了@Slf4j批注,我可以在其中添加:

@Slf4j
class Fizz {
    void doSomething() {
      log.info("We're doing something now...")
    }
}

...and Groovy would create an SLF4J logger and inject it into Fizz 's bytecode for me. ...然后Groovy会创建一个SLF4J记录器,并为我将其注入Fizz的字节码中。 It spared me from having to do the following in every single class: 这使我不必在每个班级要做以下工作:

class Fizz {
    Logger log = LoggerFactory.getLogger(Fizz)

    void doSomething() {
      log.info("We're doing something now...")
    }
}

I really miss this so far. 到目前为止,我真的很想念这个。

I'm wondering if I can use traits/mixins to do the same, but it would have to be generic so I could use it with any class: 我想知道是否可以使用traits / mixins来做到这一点,但是它必须是通用的,因此我可以将其用于任何类:

trait MyLogger[T] {
    def log = Logger.getLogger(T)
}

Then: 然后:

class Fizz extends MyLogger[Fizz] {
  def doSomething() : Unit = {
    log.info("Doing something now...")
  }
}

etc. Is this possible to do? 等。这可能吗? If so, am I close or way off base here? 如果是这样,我是在这里关闭还是离开基地?

Actually, you're on the right track with your trait: 实际上,您的性格是正确的:

trait Logging {
  lazy val log = Logger.getLogger(getClass.getName)
}

You use it like this: 您可以这样使用它:

class MyStuff extends MySuperClass with Logging {
  log.info("Setting up my stuff")
}

In fact, this is pretty much what scala-logging does - plus a few more macros to save you typing the if (log.is_LEVEL_Enabled) log._LEVEL_ (but still putting it in the final output). 实际上,这几乎是scala日志记录的全部功能-再加上一些宏以节省您键入if (log.is_LEVEL_Enabled) log._LEVEL_ (但仍将其放在最终输出中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM