Scala call logging method without “log.xxxx”

人盡茶涼 提交于 2020-01-05 02:47:27

问题


Is there a way to do the following without having to manually define the logging methods e.g. def error:

object FooBar {
  lazy val log = LoggerFactory.getLogger("AndroidProxy")
  def error(msg: String) = log.error(msg)


  def my_method(): Unit = {
    error("This is an error!")
  }
}

回答1:


replace def error with

import log.error



回答2:


If you want to log in many classes and not rewrite the logging method every time, you can create a trait

trait Logging {
    lazy val logger = LoggerFactory.getLogger(getClass())

    def error(msg: => String) = log.error(msg)
}

Then in the classes where you need logging you do...

class MyClass extend Logging {
    def method() {
        //do stuff
        error("oups!")
    }
}

It is usually a good idea to pass the msg parameter by name (using :=> String) so that the string argument is evaluated only if used.

Also, notice that getClass is now the name of the logger. Which is helpful because now the name of the logger is the name of the class extending the Logging trait and not a hardcoded name.



来源:https://stackoverflow.com/questions/14905834/scala-call-logging-method-without-log-xxxx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!