André Martins
05/03/2022, 3:39 PMwithContext(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 rightAndré Martins
05/03/2022, 6:47 PMAndré Martins
05/03/2022, 6:51 PMinterface 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
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 💪Richard Gomez
05/03/2022, 7:51 PM