Skip to content
oshai edited this page Sep 24, 2017 · 42 revisions

Welcome to the kotlin-logging wiki!

kotlin-logging is a lightweight logging framework for Kotlin. A convenient and performant logging library wrapping slf4j with Kotlin extensions kotlin-logging provides both:

  • Idiomatic way to obtain a logger without the need to specify class name
  • Enhanced logging api that integrates fluently with Kotlin

Install

Important note: kotlin-logging depends on slf4j-api. In runtime, it is also required to depend on a logging implementation. More details here.

Maven

<dependency>
  <groupId>io.github.microutils</groupId>
  <artifactId>kotlin-logging</artifactId>
  <version>1.4.6</version>
</dependency>

See full example in kotlin-logging-example-maven.

Gradle

compile 'io.github.microutils:kotlin-logging:1.4.6'

Or alternatively, download jar from github or bintray or maven-central.

Usage

Obtaining a logger

The preferred way to obtain a logger is as follows:

// Place definition above class declaration, below imports, 
// to make field static and accessible only within the file
private val logger = KotlinLogging.logger {}

Another option (less recommended) is to is to have the Companion object extends KLogging():

companion object: KLogging()

In cases the Companion object already extending other class it is recommend to implement the KLoggable interface:

companion object: Any(), KLoggable {
  override val logger = logger()
  ...
}

Other (less recommended) alternatives are:

companion object: Any(), KLoggable by NamedKLogging("com.MyClass")

Or implementing it as a non static member:

class ClassHasLogging: KLoggable {
    override val logger = logger()
}

all examples also available in tests.

Usage of logger

The most simple use is the same as with java logger:

logger.info("hello message")

For sequences that are expected to be frequently used or costly prefer lazily evaluated messages:

logger.debug { "lazy evaluated $hello message" }

(String is inside a method and gets evaluated only if debug log level is enabled at runtime)

When logging exceptions, it is also possible to use a lambda to calculate the attached message:

logger.error(exception) { "a $fancy message about the $exception" }

The complete list of methods can be found in KLogger source code.