Skip to content
Ohad Shai edited this page Nov 14, 2026 · 46 revisions

Welcome to the kotlin-logging wiki!

kotlin-logging is a lightweight multiplatform logging framework for Kotlin. On the JVM it wraps SLF4J with idiomatic Kotlin extensions, providing:

  • A concise way to obtain a logger without specifying the class name explicitly
  • Lazy {} lambda evaluation and a fluent structured logging API

Install

Important note: kotlin-logging is a logging facade, so a backend logging implementation is required at runtime. On the JVM, add org.slf4j:slf4j-api along with an SLF4J provider (such as Logback, Log4j 2, or slf4j-simple). More details are available in the SLF4J manual.

Gradle

Kotlin DSL (build.gradle.kts)

dependencies {
    implementation("io.github.oshai:kotlin-logging-jvm:8.0.7")
}

Version Catalog (gradle/libs.versions.toml)

[versions]
kotlin-logging = "8.0.7"

[libraries]
kotlin-logging-jvm = { module = "io.github.oshai:kotlin-logging-jvm", version.ref = "kotlin-logging" }
# For Kotlin Multiplatform (commonMain):
kotlin-logging = { module = "io.github.oshai:kotlin-logging", version.ref = "kotlin-logging" }
dependencies {
    implementation(libs.kotlin.logging.jvm)
}

Kotlin Multiplatform (commonMain)

kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("io.github.oshai:kotlin-logging:8.0.7")
        }
    }
}

See Multiplatform support for platform-specific details.

Groovy DSL (build.gradle)

dependencies {
    implementation 'io.github.oshai:kotlin-logging-jvm:8.0.7'
}

Maven

<dependency>
  <groupId>io.github.oshai</groupId>
  <artifactId>kotlin-logging-jvm</artifactId>
  <version>8.0.7</version>
</dependency>

See a full setup in kotlin-logging-example-maven, or browse releases on GitHub and Maven Central.

Usage

Obtaining a logger

The preferred way to obtain a logger is at top level in the file:

import io.github.oshai.kotlinlogging.KotlinLogging

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

Additional usage examples are available in the JVM test suite.

Usage of logger

In 8.x, lazy {} lambdas and fluent at<Level> { ... } blocks are the primary KLogger API. The message lambda is evaluated only when the corresponding log level is enabled at runtime (legacy non-lambda String? overloads such as logger.info("...") were removed in 8.0.0 — see the OpenRewrite migration guide when upgrading from earlier versions):

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

When logging exceptions, pass the Throwable first and compute the message lazily in the trailing lambda:

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

For structured logging (key-value payload, cause, marker), use the fluent atTrace / atDebug / atInfo / atWarn / atError builder API (on SLF4J 2.0+ and Logback backends, payload entries are forwarded as structured key-value pairs):

logger.atInfo {
    message = "Order processed"
    payload = buildMap {
        put("orderId", orderId)
        put("userId", userId)
    }
}

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

Mapped Diagnostic Context (MDC) Support

MDC attaches contextual key-value data (such as userId or requestId) to log events on the current thread. More details can be found in the SLF4J MDC documentation.

In kotlin-logging, set scoped MDC entries with withLoggingContext:

import io.github.oshai.kotlinlogging.withLoggingContext

withLoggingContext("userId" to userId) {
    doSomething()
}

Multiple pairs or a Map<String, String?> are also supported. See KotlinLoggingMDC.

MDC and threads/coroutines

Under the hood, SLF4J MDC uses ThreadLocal storage. When using Kotlin coroutines, propagate MDC entries across suspensions and thread switches by adding org.jetbrains.kotlinx:kotlinx-coroutines-slf4j:

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-slf4j:<version>")
}

Use withLoggingContextAsync inside suspend functions to scope MDC entries cleanly to the coroutine context:

import io.github.oshai.kotlinlogging.coroutines.withLoggingContextAsync

withLoggingContextAsync("userId" to userId) {
    logger.info { "Processing request in coroutine" }
}

You can also pass MDCContext() explicitly when launching coroutines from a synchronous withLoggingContext block:

import io.github.oshai.kotlinlogging.withLoggingContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.slf4j.MDCContext

withLoggingContext("kotlin" to "the moon") {
    launch(MDCContext()) {
        logger.info { "..." } // MDC context contains the mapping here
    }
}

More details in KotlinLoggingAsyncMDC and kotlinx-coroutines-slf4j.

Getting the actual Logger

When you need access to the underlying framework logger (for example, org.slf4j.Logger on JVM), cast to DelegatingKLogger<*> and read underlyingLogger:

import io.github.oshai.kotlinlogging.DelegatingKLogger

val underlying = (logger as? DelegatingKLogger<*>)?.underlyingLogger

DelegatingKLogger<*> is implemented by facade backends that wrap an external logger; direct/native logger implementations do not implement it.

More details and examples here: https://github.com/oshai/kotlin-logging/issues/20

FAQ

Q: Is method line reporting supported?

A: Yes. More details here: https://github.com/oshai/kotlin-logging/issues/11

Q: Are colored logs supported?

A: As with other framework-specific features, colored output is supported and configured in the underlying logging backend. More details here: https://github.com/oshai/kotlin-logging/issues/24

Q: What is the minimal Gradle dependency that I need in order for kotlin-logging to work and print my messages?

A: Add kotlin-logging-jvm together with an SLF4J implementation such as slf4j-simple:

dependencies {
    implementation("io.github.oshai:kotlin-logging-jvm:8.0.7")
    implementation("org.slf4j:slf4j-simple:2.0.20")
}

Q: Android R8 seems corrupting the logger name, what can I do?

A: In most cases declaring the logger in a companion object works:

companion object {
    private val logger = KotlinLogging.logger {}
}

See more details in #115.

Q: What happen if an exception is thrown when creating a log message?

A: By default it logs a message saying: Log message invocation failed: ...

On the JVM, you can configure it to rethrow the exception by passing the system property -Dkotlin-logging.throwOnMessageError in JVM args.

More details on #160.

Q: Why does KotlinLogging.logger {} inside a nested or inner class use the outer class name on JVM?

A: On JVM and Android, logger name resolution strips everything from the first $ in the binary class name so lambdas and Companion objects resolve to the enclosing class. As a result, a logger declared inside a nested or inner class (or its companion object) gets the enclosing top-level class name.

To use a separate logger name for a nested or inner class, pass the name explicitly:

private val logger = KotlinLogging.logger(Outer.Inner::class.java.name)
// or: KotlinLogging.logger("package.Outer.Inner")

See #495 for details.

Q: How do I set the log level?

A: On JVM and Android (when using SLF4J), log levels are configured in the underlying logging framework (Logback, Log4j 2, etc.).

Programmatic example for Logback:

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger
import io.github.oshai.kotlinlogging.DelegatingKLogger
import io.github.oshai.kotlinlogging.KLogger

var KLogger.level: Level?
    get() = ((this as? DelegatingKLogger<*>)?.underlyingLogger as? Logger)?.level
    set(value) {
        ((this as? DelegatingKLogger<*>)?.underlyingLogger as? Logger)?.level = value
    }

logger.level = Level.DEBUG

For Log4j, see answers here.

For multiplatform targets using direct logging (JS, Wasm, Linux, Windows, Android Native), configure KotlinLoggingConfiguration.direct.logLevel:

import io.github.oshai.kotlinlogging.KotlinLoggingConfiguration
import io.github.oshai.kotlinlogging.Level

KotlinLoggingConfiguration.direct.logLevel = Level.ERROR

See Multiplatform support and additional suggestions on StackOverflow.