Henriette's Notes

Home » Posts tagged 'scala-logging'

Tag Archives: scala-logging

scala-logging with log4j2

In this brief post I provide a minimal complete example that uses scala-logging with log4j2. scala-logging is a Scala logging library wrapping SLF4J.

Scala code

Here is a minimal complete Scala code example using scala-logging. Note that we use a companion object to define an instance of Logger that will be shared across all instances of SimpleLoggingTest.

package org.henrietteharmse.tutorial

import com.typesafe.scalalogging.Logger

class SimpleLoggingTest {
  SimpleLoggingTest.logger.trace("Hello while instance
    of SimpleLoggingTest is created.")
}

object SimpleLoggingTest {
  private val logger = Logger[SimpleLoggingTest]

  def main(args: Array[String]):Unit = {
    logger.trace("Hello from SimpleLoggingTest 
      companion object")
    val simpleLoggingTest = new SimpleLoggingTest
    try {
      throw new RuntimeException("Some error")
    } catch {
      case t : Throwable => logger.error(s"Error: 
        ${t.getMessage}")
    }    
  }
}

Log4j configuration

In this section we provide a minimal log4j.xml configuration file. It defines a trace level logger for our application code with an error level logger for all other errors. Logging for our code will be written to a file in ./logs/App.log, and all errors, originating from other code than our own code, being logged to the console.

<?xml version="1.0" encoding="UTF-8"?>
  <Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%markerSimpleName %-5p 
        %C.%M():%L - %msg %ex{full}%n"/>
    </Console>
    <File name="Log" fileName="./logs/App.log">
      <PatternLayout>
        <Pattern>%markerSimpleName %-5p %C.%M():%L 
          - %msg %ex{full}%n</Pattern>
      </PatternLayout>
    </File>    
  </Appenders>
  <Loggers>
    <Logger name="org.henrietteharmse.tutorial" 
      level="trace" additivity="false">
      <AppenderRef ref="Log"/>
    </Logger>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

SBT configuration

The build.sbt file for building this application is given below. Most importantly it states the correct dependencies for using scala-logging with the libraryDependencies setting. To get debug information from log4j, we set the system property log4j2.debug to true.
ThisBuild / scalaVersion := "2.13.2"
ThisBuild / organization := 
  "org.henrietteharmse.tutorial"

val setLog4jDebug = sys.props("log4j2.debug") = "true"

lazy val root = (project in file("."))
  .settings(
  name := "scala-logging-with-log4j2",
  libraryDependencies ++= Seq(
    "com.typesafe.scala-logging" %% "scala-logging" % 
      "3.9.2",
    "org.slf4j" % "slf4j-api" % "1.7.30",
    "org.apache.logging.log4j" % "log4j-slf4j-impl" % 
      "2.13.3"
  ),
  scalacOptions ++= Seq("-deprecation")
)

Conclusion

This post gives a minimal complete example for using scala-logging with log4j using SBT. The complete code example can be found here on GitHub.