How to set coroutine context from spring webflux WebFilter? Is it possible? I know I can use reactor context, but I'm not able to set coroutine context.
MORE DETAILS:
I want to use MDCContext to propagate MDC to slf4j. For example, I would like to get MDC from HTTP headers and then I want these values to be automatically propagated to any log I write.
Currently, I can:
- I set reactor context in WebFilter
- in every controller I get values from reactor context and put them inside MDCContext (coroutine)
As you see, this is not very convenient as I have to add extra code in the controllers.
Is there a way to automatically transform Reactor context to coroutine context? I know I can do vice versa with ContextInjector and ServiceLoader (see https://github.com/Kotlin/kotlinx.coroutines/issues/284#issuecomment-516270570), but it seems there is no such mechanism for reverse conversion.
And: Using ReactiveSecurityContextHolder inside a Kotlin Flow
UPDATE 3 (25.01.2022)
I have created a library that resolves MDC LocalThread problem in a reactive environment. I have created a special Map implementation MDC class that journey in a reactive context.
https://github.com/Numichi/reactive-logger
UPDATE 1
Use and Add context in Kotlin Coroutine.
UPDATE 2 (25.12.2021)
I use Log4j2 with slf4j. But, I think it will work another implementation (example: logback).
build.gradle.kts
(Optinonal) If you use WebFilter and writeContext via WebFlux. Would you like to put all ReactorContext copy into MDCContext, use the below code. You will experience MDCContext containing all ReactorContext elements on begin of the controller.
If you would like to use @ExceptionHandler MDCContext will drop all values that you added
MDC.put("key", "value")after the controller because the runner exit the suspended scopes. They work like code variables and code blocks. So, I recommend saving any values in exception and restore in handler from throwable instance.So you can use MDCContext (or in any class). Ofc, not need call every time
LoggerFactory.getLogger(javaClass). This can also be organized into attributes.In log4j2.xml you can reference an MDC key and load it there. Example:
<PatternLayout pattern="%mdc{context_map_key}">Log4J Plugin
Add more one dependency with
annotationProcessorWrite plugin. Ofc, it is a minimalist:
And log4j2.xml what in
project/src/main/resources/log4j2.xml.