Last active
April 14, 2023 15:02
-
-
Save monosoul/c40226a45f4dd0710ad5383879312a1d to your computer and use it in GitHub Desktop.
MDC helper function for Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.slf4j.MDCContext | |
import kotlinx.coroutines.withContext | |
import org.slf4j.MDC | |
inline fun <T> withMdc(vararg attributes: Pair<String, Any?>, block: () -> T): T { | |
val oldAttributes = MDC.getCopyOfContextMap() ?: emptyMap() | |
attributes.forEach { (key, value) -> | |
value?.apply { | |
MDC.put(key, toString()) | |
} | |
} | |
return try { | |
block() | |
} finally { | |
MDC.setContextMap(oldAttributes) | |
} | |
} | |
suspend fun <T> withMdcContext(vararg attributes: Pair<String, Any?>, block: suspend CoroutineScope.() -> T): T { | |
val mdcContext = withMdc(*attributes) { MDCContext() } | |
return withContext(mdcContext, block) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: