Log4j 2 API

Scala API

Log4j 2 具有一个伴随的 Log4j Scala 项目,其中包含一个方便的Logger API Scala 包装器。

Requirements

Log4j 2 Scala API 依赖于 Log4j 2 API,Scala 运行时库和反射。它目前支持 Scala 2.10、2.11 和 2.12. 有关将其包含在 SBT,Maven,Ivy 或 Gradle 项目中的信息,请参见instructions

Example

import org.apache.logging.log4j.scala.Logging
import org.apache.logging.log4j.Level

class MyClass extends BaseClass with Logging {
  def doStuff(): Unit = {
    logger.info("Doing stuff")
  }
  def doStuffWithLevel(level: Level): Unit = {
    logger(level, "Doing stuff with arbitrary level")
  }
}

调用 logger.info()的输出将根据所使用的配置而有很大不同。有关更多详细信息,请参见Configuration部分。

Substituting Parameters

通常,日志记录的目的是提供有关系统中正在发生的事情的信息,这需要包括有关被操纵对象的信息。在 Scala 中,您可以使用string interpolation实现:

logger.debug(s"Logging in user ${user.getName} with birthday ${user.calcBirthday}")

由于 Scala Logger 是用宏实现的,因此只有在启用调试日志记录后,才会进行 String 构造和方法调用。

Logger Names

大多数日志记录实现都使用分层方案,以使日志 Logger 名称与日志记录配置相匹配。在此方案中,Logger 名称层次结构由“。”表示。Logger 名称中的字符,其格式与 Java/Scala 软件包名称所使用的层次结构非常相似。记录 Feature 将根据正在使用的类自动命名 Logger。

有关更多详细信息,请参见Log4j Scala项目。