Slf4j's MDC and Coroutines

Hi guys,

I hope I’m in the right place to ask my question. If that’s not the case, please tell me.

My question in short is: is there a way to hook into the activation/execution of basically every coroutine and do some stuff there?
In Spring WebFlux, specifically reactor, there’s the concept of Hooks. There you can hook into the activation of a mono/flux operator and do stuff before the code inside it is executed. I’m searching for a similar concept for coroutines.

My particular use case is the following:

I rewrite rest controllers to be suspending functions instead of returning Mono and Flux.

I have a Spring RestController like the following:

@GetMapping("/dummy")
suspend fun dummyEndpoint(): ResponseEntity<String> {
    logger.debug("dummy")
    return ResponseEntity.ok("OK")
}

The question is how to propagate the MDC context. I could do the following:

@GetMapping("/dummy")
suspend fun dummyEndpoint(): ResponseEntity<String> {
    withContext(MDCContext()) {
        logger.debug("dummy")
        return ResponseEntity.ok("OK")
   }
}

from this package.

I’m searching for a solution for not having to explicitly do this. In WebFlux I could have a standalone configuration, where I use reactor hooks to hook into every operator and execute setup code.

For the sake of completeness: I solved it using aspects after all. The aspect will insert the withContext... part before invoking the functions in question.