MDC in Java Logging
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
MDC stands for Mapped Diagnostic Context, and it's a per-thread key-value map that SLF4J and Logback provide.
The idea is that you put a value into it once — typically at the very start of a request — and from then on it's automatically attached to every log line produced on that thread, without you having to pass it into each log call. The classic use case is a correlation ID. put with the key requestId.
Then, anywhere downstream — in the controller, the service, the repository — every log line automatically includes that request ID, because I've configured my log pattern to print the MDC value using the percent-X-curly-brace-requestId syntax.
That means when a user reports a problem, I can grab their request ID and instantly pull up every single log line for just that one request, even though it touched a dozen classes. The most important gotcha, and the thing interviewers love to check, is that you must clear the MDC when the request finishes. Application servers use thread pools, so the same thread gets reused for the next request.
clear in a finally block, the old request ID leaks into the next request's logs, and now your correlation is wrong and misleading. The other thing to know is that MDC is thread-local, so it doesn't automatically follow you if you spawn a new thread or run something asynchronously — you have to copy the context over yourself.
But for normal request-scoped logging, MDC is the clean, standard way to tie all of a request's logs together.
MDC in Java Logging
Direct Answer
MDC is a provider-supported diagnostic context exposed by SLF4J as key-value data associated with the current thread. A logging pattern or structured encoder must include those keys before they appear in output. MDC does not automatically cross executor, async, or reactive boundaries; copy or bridge context deliberately, and restore or clear values on pooled threads.
Deep Dive & Architecture
MDC—Mapped Diagnostic Context—lets code attach fields such as requestId to logging events without passing that value to every log call. The SLF4J API exposes the context, while the active logging provider stores and renders it.
The output configuration must include the MDC field, for example %X{requestId}, or use a structured encoder that reads MDC. Setting a value alone does not guarantee that every appender prints it.
Classic MDC is associated with the current thread. Executor tasks, @Async, CompletableFuture, and reactive pipelines may run elsewhere, so context needs an explicit propagation mechanism suited to that framework. When code places a value on a reusable thread, restore the old context or clear it in finally; MDC.putCloseable can help scope a value.
Code Example
import org.slf4j.MDC;
import java.util.UUID;
public class RequestIdFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
MDC.put("requestId", UUID.randomUUID().toString()); // set once per request
try {
chain.doFilter(req, res); // every log line downstream now carries requestId
} finally {
MDC.clear(); // CRITICAL: clear so pooled threads don't leak the value
}
}
}
<!-- logback pattern: %X{requestId} prints the MDC value on every line -->
<pattern>%d %-5level [%X{requestId}] %logger - %msg%n</pattern>
Common Mistakes & Pitfalls
- Not clearing MDC: thread pools reuse threads, so a leftover
requestIdleaks into the next request's logs. AlwaysMDC.clear()in afinally. - Expecting it to cross threads: MDC is thread-local; spawning a new thread or async task loses it unless you copy it over.
- Putting huge objects in MDC: keep it to small identifiers, not whole payloads.
Check your understanding
Answer these without looking back at the article.
- What are debugging and logging and why do they matter from day one? Debugging is finding and fixing defects; logging is recording what your program did — together they are how you understand code that isn't doing what you expect.
- Why is logging important in a Java backend application?
- What should you log in a Java backend application?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.