MDC in Spring Controller Advice Logging: Step-by-Step
In this article
To make the Mapped Diagnostic Context (MDC) available during logging inside a Spring @ControllerAdvice, you need to capture the MDC context at the point of the exception and restore it in the advice method. This works because MDC values are thread-local, and while the advice runs on the same thread that threw the exception, the context is already set by your logging filter. The key is to ensure your MDC filter runs before the controller, and to avoid clearing the MDC prematurely. Below is a practical guide to set this up.
What You'll Need
- A Spring Boot (or Spring MVC) application with SLF4J and Logback (or another SLF4J binding) on the classpath.
- A logging filter that populates MDC (e.g., a servlet filter that puts request IDs or user IDs). If you don't have one, you'll create one.
- Basic familiarity with Spring's
@ControllerAdviceand@ExceptionHandler.
Step-by-Step
- Create an MDC filter (if you don't have one). Implement a
javax.servlet.Filter(orjakarta.servlet.Filterin Spring Boot 3+) that puts values into MDC before the request proceeds, and clears them after. For example, put a request ID:MDC.put("requestId", UUID.randomUUID().toString());indoFilter, then callchain.doFilter(), and finallyMDC.clear()in afinallyblock. Register this filter as a@Beanor via@WebFilterwith@Component. - Ensure the filter runs before the controller. Spring Boot auto-registers filters with a default order. If you have multiple filters, you can annotate yours with
@Order(Ordered.HIGHEST_PRECEDENCE)to make it run early. The filter must execute before the dispatcher servlet, which is the default behavior for servlet filters. - Create your
@ControllerAdviceclass. Annotate a class with@ControllerAdvice. Inside, define an@ExceptionHandlermethod for the exceptions you want to handle. For example:@ExceptionHandler(Exception.class). - Log inside the advice method. In the advice method, use a logger (e.g.,
LoggerFactory.getLogger(YourAdvice.class)) to log the exception. Because the MDC filter set values on the thread, and the advice runs on the same thread (the request thread), the MDC values are automatically available in the log output. For example:log.error("Exception occurred", ex);. - Do not clear MDC inside the advice. The MDC is thread-local and will be cleared by the filter after the request completes. If you call
MDC.clear()in the advice, you'll lose the context for any subsequent logging in that thread (though it's rare, but it can affect async processing). Leave the clearing to the filter. - Test with a sample endpoint. Create a controller that throws an exception. Hit that endpoint and check the logs. You should see the MDC values (e.g., requestId) in the log lines produced by the advice.
- Configure your logging pattern to include MDC. In
logback.xml(orapplication.properties), add%X{requestId}to your pattern. For example:%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %X{requestId} - %msg%n. This ensures the MDC value appears in the log output.
Common Mistakes
- Clearing MDC too early. If you clear MDC in the advice method, the values vanish for any subsequent logging in that thread. Let the filter handle it.
- Filter not running. If your filter isn't registered, MDC is never populated. Make sure the filter is a Spring bean or annotated with
@Componentand@WebFilter. - Using a different thread. If your advice method is annotated with
@Asyncor runs on a different thread, MDC won't be available. Avoid that unless you manually propagate MDC. - Not including MDC in the log pattern. Even if MDC is set, if your log pattern doesn't include
%X{key}, you won't see it.
Tips
- Use a unique key per request. A request ID is common, but you can also add user IDs, session IDs, or tenant IDs.
- Consider using a OncePerRequestFilter. Extend
OncePerRequestFilterto ensure the filter runs only once per request, even with forwarded requests. - For async requests, propagate MDC manually. If you use
@Asyncor returnCallable, you need to copy MDC to the new thread. UseMDC.getCopyOfContextMap()and set it in the new thread. - Test with a real exception. Use a debugger or a simple endpoint that throws an exception to verify the MDC appears in the advice log.
Troubleshooting
If MDC values are missing in the advice logs:
- Check that the filter is actually executed. Add a log statement in the filter to confirm.
- Verify the filter order. If another filter clears MDC before your advice runs, that could be the issue.
- Check if the exception is thrown before the filter sets MDC. For example, if the filter is mapped after the dispatcher servlet, it won't run for controller exceptions. Ensure the filter is mapped to
/*. - Confirm that the log pattern includes
%X{key}. If not, you won't see the value.
If the filter isn't being picked up:
In Spring Boot, you can register a filter as a @Bean of type Filter. Alternatively, use @Component + @WebFilter and enable @ServletComponentScan on your main application class (if not already enabled).
If MDC is cleared unexpectedly:
Look for any MDC.clear() calls in your code, especially in exception handlers or interceptors. Also, check if you have a custom HandlerInterceptor that clears MDC in afterCompletion—that runs before the advice? Actually, afterCompletion runs after the view is rendered, but the advice runs during exception resolution, which is before that. Still, avoid clearing in interceptors.
Frequently Asked Questions
Can I use MDC in a @RestControllerAdvice as well?
Yes, @RestControllerAdvice is a specialized @ControllerAdvice that also adds @ResponseBody. The MDC behavior is identical.
Does MDC work with reactive Spring WebFlux?
No, MDC is thread-local and doesn't work with reactive non-blocking threads. For WebFlux, you need to use a reactive context or a library like micrometer-tracing that propagates context differently.
What if I have multiple exception handlers in the same advice?
Each @ExceptionHandler method will have access to the same MDC because they run on the same thread. No extra setup needed.
Can I set MDC values inside the advice method itself?
Yes, you can put additional values into MDC inside the advice method, but be aware they will persist until the filter clears them. That might be useful for adding error codes, but it's not necessary for the basic context.
How do I propagate MDC to an async task started in the advice?
If you spawn a new thread, copy the MDC context map using MDC.getCopyOfContextMap() and set it in the new thread with MDC.setContextMap() at the start of the thread's runnable.
Is there a performance impact of using MDC?
Minimal. MDC is a simple thread-local map. The overhead is negligible compared to I/O operations like logging.