MDC logging with @Async @Scheduled threads in spring boot
if you have already ran thru a problem with MDC context based logging in multithreaded environment, you probably know the pain of missing essential log placeholders.
Here lets take an example of a log with MDC context based logging
We get user printed in the logs as follows
Now if we have an @Async task, we don’t see the user details in logs for the task
To get MDC context copied to Async thread Spring provides a way to decorate the task runnable implementations, where we can provide way to copy MDC context
@autowire the decorator
this would supply the decorator to executor and you would see the logs getting copied to async threads
updating scheduling threads is tricky, it does not allow any task decorator directly, take following example
As you can see, USER is blank
One of they way would be to Intercept all TaskSchedular implementations & decorate the Runnables
It works! you can see the MDC is copied to child threads.