Hello, I’m following <this> approach in order to g...
# spring
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
whenever I put something in MDC, also using Mono
contextWrite(Context.of(coroutineContext[MDCContext.Key]?.contextMap ?: emptyMap()))
when calling WebFilter base
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)

    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()
        .contextWrite(Context.of(MDC_REACTOR_CONTEXT_KEY, mdcContextMap))
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
and tada 💪