Apache logging services logo Apache log4j logo

Log4j Scala 2.12 API

Requirements

Log4j Scala API for Scala 2.12 requires Log4j API, Java 8, the Scala runtime library, and the Scala reflection library. To use Log4j as a logging implementation, then Log4j Core must also be included. Instructions on using these dependencies are in the dependency information page, and additional information is included in the Log4j artifacts page.

Example Usage

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

Configuration

Log4j Scala 2.12 API uses the standard Log4j configuration plugins. This supports XML, properties files, and a configuration builder DSL by default, and it optionally supports JSON and YAML formats with some additional Jackson dependencies.

Substituting Parameters

In the Java API, parameters to a log message are interpolated using various strategies. In the Scala API, string interpolation is used instead. As all logger methods are implemented as macros, string construction and method invocations will only occur when logging is enabled for the given log level. For example:

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

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.