kotlin-logging Documentation

repository·master·Indexed 25 days ago

https://github.com/oshai/kotlin-logging

A lightweight, multiplatform logging facade for Kotlin that provides an idiomatic wrapper around SLF4J. It features lazy-evaluated log messages via lambdas, fluent logging with payloads, and coroutine-safe MDC context via withLoggingContextAsync. The library supports SLF4J 1 and 2, requiring a separate logging implementation such as Logback or Log4j2 at runtime.

Tokens
1.4K
Snippets
7
Records
12
Agent score
85%

What's inside kotlin-logging

  1. Migrate from 1.x to 2.x

    master

    When upgrading from version 1.x to 2.x, note the following breaking changes:

    1. Artifact Name Change: The JVM artifact name has changed from kotlin-logging to kotlin-logging-jvm to comply with the multiplatform schema.
    2. Kotlin Version Requirement: Version 2.x requires Kotlin >= 1.4.

    Recommendation: For JVM-only library owners, using 1.x is still acceptable, but 2.x is recommended for all other use cases.

  2. Migrating from version 3/4 to version 5+

    master

    Version 5 introduced breaking changes. If you are upgrading:

    • The Maven Group ID changed from io.github.microutils to io.github.oshai.
    • The root package changed from mu to io.github.oshai.kotlinlogging.
    • slf4j-api is no longer provided automatically; you must include it in your dependencies.
    • Version 5+ supports both SLF4J 1 and 2.
  3. Install kotlin-logging

    master

    To use kotlin-logging in a JVM project, add the kotlin-logging-jvm dependency.

    Important: kotlin-logging is a facade. You must also provide a logging implementation (like Logback, Log4j2, or slf4j-simple) at runtime to see any output. If you only want to log to stdout for testing, you can add org.slf4j:slf4j-simple:2.0.3.

    ### Gradle
    ```Groovy
    implementation 'io.github.oshai:kotlin-logging-jvm:7.0.3'

    Maven

    <dependency>
      <groupId>io.github.oshai</groupId>
      <artifactId>kotlin-logging-jvm</artifactId>
      <version>7.0.3</version>
    </dependency>
  4. Use `withLoggingContextAsync` for coroutine-safe MDC context

    master

    Use withLoggingContextAsync to wrap a block of suspending code with a specific SLF4J MDC context. This ensures that the provided key-value pairs are available in the MDC during the execution of the block.

    By default, the function restores the previous MDC context once the block completes. You can disable this restoration by setting restorePrevious = false.

    withLoggingContextAsync("userId" to "A_USER_ID") {
        // The MDC context will contain the mapping of "userId"=>"A_USER_ID"
        // during this log statement.
        logger.info { "..." }
    }
    // The block will restore The MDC context so that it no longer contains
    // the mapping of "userId"=>"A_USER_ID"
    
    withLoggingContextAsync("userId" to "ANOTHER_USER_ID", restorePrevious = false) {
        logger.info { "..." }
    }
    // The MDC context will retain the mapping of "userId"=>"ANOTHER_USER_ID",
    // as the previous context restoration was disabled.
  5. Define a logger using KotlinLogging.logger

    master

    You can define a logger without explicitly specifying the class name by using the empty lambda syntax. Placing the definition above the class declaration makes the field static.

    import io.github.oshai.kotlinlogging.KotlinLogging
    
    private val logger = KotlinLogging.logger {} 
    
    class FooWithLogging {
        val message = "world"
        fun bar() {
            logger.debug { "hello $message" }
        }
    }
  6. Use fluent logging with payloads

    master

    Use the atLevel API (e.g., atWarn) to build logs fluently, allowing you to attach a cause and a structured payload.

    logger.atWarn {
        message    = "foo $bar"
        cause      = exception
        payload    = buildMap(capacity = 3) {
            put("foo", 1)
            put("bar", "x")
            put("obj", Pair(2, 3))
        }
    }
  7. Access the underlying logger via KLogger.underlyingLogger

    master
    In version 1.4.6 and later, KLogger provides an underlyingLogger property. This allows you to access the actual logger implementation, which is useful for operations such as setting log levels programmatically.