Hello, I’m following <this> approach in order to g...
# spring
a
Hello, I’m following this approach in order to get coroutine wrappers for Webflux WebFilters and I’m now trying to propagate MDC context in order to have it on my controllers. Im using
withContext(MDCContext())
whenever I put something in MDC, also using Mono
contextWrite(Context.of(coroutineContext[MDCContext.Key]?.contextMap ?: emptyMap()))
when calling WebFilter base
chain
Although this is not working and I suspect that is due to passing the coroutine context to the ReactorContext somehow I’m not doing it right
Figured it out!
Basically I have this code in order to add filters using coroutines
Copy code
interface CoWebFilter : WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> = mono(MDCContext()) {
        coFilter(exchange, chain)
        null
    }

    suspend fun coFilter(exchange: ServerWebExchange, chain: WebFilterChain)
}

const val MDC_REACTOR_CONTEXT_KEY = "MDCReactorContextKey"

suspend fun WebFilterChain.coFilter(exchange: ServerWebExchange) {
    val mdcContextMap = coroutineContext[MDCContext.Key]?.contextMap ?: emptyMap()
    filter(exchange)
        .contextWrite(Context.of(MDC_REACTOR_CONTEXT_KEY, mdcContextMap))
        .awaitSingleOrNull()
}
on the controller you simply can obtain that mdc context via coroutine context since reactor fills that in for you from reactor context
Copy code
coroutineContext[ReactorContext.Key]?.context?.getOrDefault<MDCContextMap>(MDC_REACTOR_CONTEXT_KEY, emptyMap())
This last snippet just gets the passed MDCContext from by the filter, then you simply just wrap that inside a
withContext
and tada 💪