All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.mu.KotlinLoggingMDC.kt Maven / Gradle / Ivy

There is a newer version: 9.8.0.76914
Show newest version
package mu

import org.slf4j.MDC

/**
 * Use a pair in MDC context. Example:
 * ```
 * withLoggingContext("userId" to userId) {
 *   doSomething()
 * }
 * ```
 */
inline fun  withLoggingContext(pair: Pair, body: () -> T): T =
    MDC.putCloseable(pair.first, pair.second).use { body() }

/**
 * Use a vary number of pairs in MDC context. Example:
 * ```
 * withLoggingContext("userId" to userId) {
 *   doSomething()
 * }
 * ```
 */
inline fun  withLoggingContext(vararg pair: Pair, body: () -> T): T {
    try {
        pair.forEach { MDC.put(it.first, it.second) }
        return body()
    } finally {
        pair.forEach { MDC.remove(it.first) }
    }
}

/**
 * Use a map in MDC context. Example:
 * ```
 * withLoggingContext(mapOf("userId" to userId)) {
 *   doSomething()
 * }
 * ```
 */
inline fun  withLoggingContext(map: Map, body: () -> T): T {
    try {
        map.forEach { MDC.put(it.key, it.value) }
        return body()
    } finally {
        map.forEach { MDC.remove(it.key) }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy