Skip to content

Latest commit

 

History

History
53 lines (38 loc) · 1.42 KB

File metadata and controls

53 lines (38 loc) · 1.42 KB

Async Context and MDC

Circumstance

  • You are using the SLF4J MDC.
  • You are using the Async Context.
  • Some properties of the context must be included in the log entries.

Using

In your IoC container register the AsyncContextMdcAdapter class as a singleton dependency of the application.

On the application startup invoke the run() method:

AsyncContextMdcAdapter mdcAdapter;
...
mdcAdapter.run();

For example, the context contains the userId property and you are using log4j2. To add this property to the log entries, mention it in the pattern layout as %X{userId}.

Spring Boot

If you are using Spring Boot, add the next registration:

@Bean
public AsyncContextMdcAdapter mdcAdapter(IAsyncContext context) {
    return new AsyncContextMdcAdapter(context);
}

And a handler of the application startup event:

@Component
public class AsyncContextMdcAdapterRunner {

    private final AsyncContextMdcAdapter mdcAdapter;

    ...

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationStarted() {
        mdcAdapter.run();
    }
}