jvmMain.mu.KotlinLoggingMDC.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sonarlint-core Show documentation
Show all versions of sonarlint-core Show documentation
Common library used by some SonarLint flavors
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) }
}
}