Log4j2 for Kotlin

Motivation

Logging is a common good practice in software engineering. It enables you to monitor applications in production to gather information about crashes and other malfunctions for further analysis. It is the “little brother” of debugging and often a precursor for setting up test cases which can lead to reproducing the bugs on the developers machine.

Log4j2 is version 2 of the very famous Apache logging library log4j from the Java ecosystem.

This article describes a minimal working solution for log4j2 with Kotlin and Gradle.

Dependencies

To get started with log4j2 add the following lines to your build.gradle file in the dependency section:

compile "org.apache.logging.log4j:log4j-api-kotlin:1.0.0"
compile "org.apache.logging.log4j:log4j-api:2.11.1"
compile "org.apache.logging.log4j:log4j-core:2.11.1"

Configuration

Create a file with the name log4j2.properties under src/resources with the content:

status = error

appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n

rootLogger.level = error
rootLogger.appenderRef.stdout.ref = LogToConsole

Logger

In your code you can insert the log statements the following way:

import org.apache.logging.log4j.kotlin.logger

fun main() {
    val log = logger("Main")
    log.trace("Trace")
    log.debug("Debug")
    log.info("Info")
    log.warn("Warn")
    log.error("Error")
    log.fatal("Fatal")
}

Log Levels

In the configuration file you can set the log level.

e.g. rootLogger.level = error will log all log message which are more severe than error including error -> (fatal and error)

| Log message |       |               |       |       |      |      |       |       |     |
|-------------|-------|---------------|-------|-------|------|------|-------|-------|-----|
|             | trace |               |       |       |      |      |       | x     | x   |
|             | debug |               |       |       |      |      | x     | x     | x   |
|             | info  |               |       |       |      | x    | x     | x     | x   |
|             | warn  |               |       |       | x    | x    | x     | x     | x   |
|             | error |               |       | x     | x    | x    | x     | x     | x   |
|             | fatal |               | x     | x     | x    | x    | x     | x     | x   |
|             |       | off           | fatal | error | warn | info | debug | trace | all |
|             |       | Configuration |       |       |      |      |       |       |     |