Skip to content

Instantly share code, notes, and snippets.

@monosoul
Last active April 14, 2023 15:02
Show Gist options
  • Save monosoul/c40226a45f4dd0710ad5383879312a1d to your computer and use it in GitHub Desktop.
Save monosoul/c40226a45f4dd0710ad5383879312a1d to your computer and use it in GitHub Desktop.
MDC helper function for Kotlin
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)
}
@monosoul
Copy link
Author

monosoul commented Apr 12, 2023

Usage example:

    withMdc(
        "userId" to user.id,
        "timestamp" to LocalDateTime.now(),
    ) {
        logger.info("User called a method")
        someOtherMethodWhereYouWantToPropagateTheContext()
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment