https://kotlinlang.org logo
n

Nikky

11/12/2020, 11:04 AM
how can i retrieve MDC from a CoroutineContext in a exception handler ? the code looks like so currently
Copy code
private val exceptionHandler = CoroutineExceptionHandler { context, e -> GlobalScope.launch(MDCContext() + context) {
can i somehow do
context.getCopyOfContextMap()
?
o

oshai

11/12/2020, 7:44 PM
How about keeping MDCContext() in a var?
n

Nikky

11/12/2020, 7:52 PM
the issue seems to be that on coroutine boundary the contextMap from the coroutineContext is used to restore the MDC ie. when you put
MDC.put("extra", "value")
inside the coroutineScope and before a suspending call then after that call the new value will be gone so i tried something where i manually "save" the MDC state to the coroutineContext
Copy code
fun CoroutineScope.storeMDC() {
    <http://logger.info|logger.info> { "storeMDC" }
    coroutineContext[MyMDCContext.Key]?.apply {
        contextMap = MDC.getCopyOfContextMap()
    }
}
but this does not work.. first of all
contextMap
is readonly and even when i made a copy of the class (
MyMDCContext
) it does not work.. something still restores a empty MDC context after a suspending call
all that because its kinda ugly to only be able to safely use MDC inside a
withContext(MDCContext()) { ... }
causing very indented code even faster
o

oshai

11/12/2020, 7:55 PM
if i remember correctly the map is copied to the coroutine, and poped when return, so yes, its not possible to add values and get them outside
n

Nikky

11/12/2020, 7:58 PM
i was hoping i could update the coroutineCOntext varaible from inside the context, so it ALSO restores that value, but nothing is that easy
o

oshai

11/12/2020, 8:55 PM
I think the place to ask for it is coroutines
n

Nikky

11/13/2020, 3:24 PM
i did
39 Views