I'm working on an application that uses SLF4J and ...
# coroutines
k
I'm working on an application that uses SLF4J and MDC. In one place, there is some code like this:
Copy code
MDC.put(some context...)
withContext(<http://Dispatchers.IO|Dispatchers.IO> + MDCContext()) {
   ...some asynchronous processing...
}
// At this point MDC is clear, the original context has disappeared!
After the
withContext
call, the entries in the MDC have all been removed and the context map is empty. Does anyone have any clues how I can go about figuring out how/why/where this context is getting zapped?
s
Since
withContext
changes dispatchers, there's no guarantee that line 5 is running on the same thread as line 1. You'd need the
MDCContext
installed higher up if you want to rely on its contents outside the
withContext
block.
k
Ah, I see, thank you Sam
Looking at the logs from before and after the
withContext
call, it seems to be the same thread (at least same ID) on lines 1 and 5. Is there any other way the context can disappear? (I'll change this anyway, to make sure the context is saved higher up.)
s
Perhaps
MDCContext
is already installed in the context higher up? Since
withContext
is a suspension point, it would trigger the
MDCContext
to restore its original saved state when
withContext
returns.
There's a comparable example in the docs showing how the context disappears after calling
delay()
.
k
Thanks Sam, it is indeed being done higher up the call tree.
👍 1
s
I wish there was an easier way to integrate coroutines with thread locals 😞 this stuff hurts my brain every single time I have to think about it
1