Apache logging services logo Apache log4j logo

Log4j 2 API

Scala API

Log4j 2 has a companion Log4j Scala project that contains a convenient Scala wrapper for the Logger API.

Requirements

Log4j 2 Scala API is dependent on the Log4j 2 API, Scala runtime library and reflection. It currently supports Scala 2.10, 2.11 and 2.12. See instructions on including this in an SBT, Maven, Ivy, or Gradle project.

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")
  }
}
                

The output from the call to logger.info() will vary significantly depending on the configuration used. See the Configuration section for more details.

Substituting Parameters

Frequently the purpose of logging is to provide information about what is happening in the system, which requires including information about the objects being manipulated. In Scala, you can use string interpolation to achieve this:

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

Since the Scala Logger is implemented with macros, the String construction and method invocations will only occur when debug logging is enabled.

Logger Names

Most logging implementations use a hierarchical scheme for matching logger names with logging configuration. In this scheme the logger name hierarchy is represented by '.' characters in the logger name, in a fashion very similar to the hierarchy used for Java/Scala package names. The Logging trait will automatically name the Logger accordingly to the class it is being used in.

Please see the Log4j Scala project for more details.