Sub topic 10
Adding request context with MDC
This chapter assumes you can write SLF4J log statements and edit a logback.xml file. You should also know the basics of Java threads and ExecutorService. Everything here builds on the Logback pattern syntax from the previous chapter.
The problem: log lines without context
A server handles many requests at once. Each request writes several log lines, and the lines from different requests interleave in the output:
10:15:02.114 INFO Handling request
10:15:02.115 INFO Handling request
10:15:02.130 WARN Inventory low
10:15:02.131 ERROR Payment declinedYou cannot tell which request produced the warning or the error. One fix is to pass the request ID into every method and include it in every message. That clutters method signatures, and a single forgotten message breaks the trail.
The Mapped Diagnostic Context (MDC) solves this. It is a map of string keys to string values that the logging framework keeps for the current thread. You put a value in once. The backend then reads the map each time a log event is created, so a pattern can print the value on every line without any logging call mentioning it.
How MDC works
org.slf4j.MDC is a static facade. The SLF4J API defines the methods, and the backend supplies an MDCAdapter that stores the data. Logback's adapter keeps the map in a ThreadLocal, so each thread sees only its own entries.
The main operations are:
| Method | Effect |
|---|---|
| `MDC.put(key, value)` | Sets a value for the current thread. The key must not be `null`. |
| `MDC.get(key)` | Returns the current value, or `null` if absent. |
| `MDC.remove(key)` | Deletes one entry. |
| `MDC.clear()` | Deletes all entries for the current thread. |
| `MDC.putCloseable(key, value)` | Sets a value and returns an `MDCCloseable` that removes the key when closed. |
| `MDC.getCopyOfContextMap()` | Returns a copy of the whole map, or `null` if there is none. |
| `MDC.setContextMap(map)` | Replaces the whole map for the current thread. |
Values are strings. Convert numbers and other objects yourself before storing them.
Setting a value safely
The simplest correct pattern is putCloseable in a try-with-resources block. The entry is removed when the block exits, even if an exception is thrown.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class RequestHandler {
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
public void handle(String requestId) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", requestId)) {
log.info("Handling request");
validate();
log.info("Request complete");
}
}
private void validate() {
log.debug("Validating input");
}
}The validate method never mentions the request ID, yet its output carries it. This is the main benefit of MDC: code deep in the call stack gets context from the caller's thread.
If you need several keys, nest the resources or use put and remove inside try/finally:
import org.slf4j.MDC;
public class MultiKey {
public void run(String requestId, String userId) {
MDC.put("requestId", requestId);
MDC.put("userId", userId);
try {
// application work that logs
} finally {
MDC.remove("requestId");
MDC.remove("userId");
}
}
}MDCCloseable.close() calls MDC.remove(key). It does not restore a previous value for that key. If an outer scope set requestId and an inner scope puts the same key, the outer value is gone after the inner block closes. Use different keys for nested scopes, or save and restore the old value yourself.
Printing MDC values with Logback
The MDC map only appears in output if the encoder asks for it. In a Logback pattern, %X{key} prints one value, and %X alone prints the whole map.
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] [%X{requestId:-none}] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>The :-none part is a default. Without it, a missing key prints as an empty string. With it, lines logged outside any request show none, which makes missing context easy to spot.
With this configuration, a call to handle("req-7f3a") produces lines like these:
10:15:02.114 INFO [main] [req-7f3a] RequestHandler - Handling request
10:15:02.115 DEBUG [main] [req-7f3a] RequestHandler - Validating input
10:15:02.116 INFO [main] [req-7f3a] RequestHandler - Request completeThe DEBUG line appears only if the logger's level allows it. This example config sets the root level to INFO, so that line would be filtered out unless you lower the level for the package.
Where to set and clear context
Set MDC values at the boundary where work enters your application, and clear them at the point where that work ends. Typical boundaries are:
- a servlet filter or HTTP interceptor
- a message listener callback
- a scheduled job entry point
- a
mainmethod for a batch run
Doing this in one place keeps the rest of the code free of MDC calls. The boundary is also where you can read a trace or correlation ID from an incoming header and reuse it, so one ID follows a request across services.
import java.util.UUID;
import org.slf4j.MDC;
public class CorrelationBoundary {
public void onRequest(String incomingId, Runnable work) {
String id = (incomingId == null || incomingId.isBlank())
? UUID.randomUUID().toString()
: incomingId;
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", id)) {
work.run();
}
}
}Treat anything that comes from outside as untrusted before you log it. A header value containing newlines can forge extra log lines. Strip or reject control characters, and limit the length.
Threads and stale values
Because the map belongs to a thread, two problems follow.
Thread pools leak context. Pool threads are reused. If a task sets requestId and never removes it, the next task on that thread logs the old ID. The log then blames the wrong request, which is worse than having no context.
Child threads do not inherit context. When a request handler hands work to an executor, the worker thread starts with an empty map. Logback does not copy the parent's map to threads created later (older versions did, through an inheritable thread local, but that caused its own leaks). You must pass the context across yourself: capture the map on the submitting thread, install it on the worker, and restore the worker's previous state afterwards.
import java.util.Map;
import java.util.concurrent.Executor;
import org.slf4j.MDC;
public final class MdcExecutor implements Executor {
private final Executor delegate;
public MdcExecutor(Executor delegate) {
this.delegate = delegate;
}
@Override
public void execute(Runnable task) {
Map<String, String> captured = MDC.getCopyOfContextMap();
delegate.execute(() -> {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (captured != null) {
MDC.setContextMap(captured);
} else {
MDC.clear();
}
try {
task.run();
} finally {
if (previous != null) {
MDC.setContextMap(previous);
} else {
MDC.clear();
}
}
});
}
}getCopyOfContextMap() can return null, so the code checks for it. The copy is taken when the task is submitted, so later changes on the submitting thread do not affect the task.
The same limit applies to asynchronous code such as CompletableFuture callbacks and reactive pipelines. A callback may run on a different thread than the one that started it. Wrap those executors, or use the context-propagation support your framework provides.
Virtual threads do not change the model. Each virtual thread has its own thread-local state, so each has an independent MDC map, and a new virtual thread starts empty. Cleanup still matters when you reuse a virtual thread for several jobs.
MDC and System.Logger
System.Logger has no MDC of its own. A call like LOG.log(Level.INFO, "msg") carries only a level, a message, and optional parameters or a throwable. MDC is part of the SLF4J API and the Logback backend.
If you route System.Logger output into SLF4J with the bridge from a later chapter, the events end up in Logback. Logback then reads the current thread's MDC map when it formats them, so %X{requestId} works for JDK and library messages too. You set the values through org.slf4j.MDC, and the System.Logger calls need no changes.
Common errors
- The value never appears. The pattern lacks
%X{key}, or the key name differs inputand in the pattern. Key names are case-sensitive. - The value appears as empty or
none. The log call ran on another thread, or after thetryblock closed. - Wrong ID on a line. An earlier task did not clean up on a pooled thread.
IllegalArgumentExceptionfromMDC.put. The key wasnull.- Nothing happens with
NOPMDCAdapter. If no SLF4J provider is on the classpath, SLF4J falls back to a no-op adapter andMDC.getreturnsnull. Check for the missing-provider warning at startup. - Sensitive data in logs. Anything you put in MDC prints on every line. Do not store passwords, tokens, or full personal data. Prefer opaque IDs.
Exercises
Exercise
A service uses a fixed thread pool. A task sets MDC.put("requestId", id) at its start and never removes it. What can go wrong, and what are two ways to prevent it?
Show answer
The pool thread keeps the entry after the task finishes, so a later task that runs on the same thread and logs without setting its own ID will print the earlier request's ID, which misattributes log lines. Prevent it by wrapping the task body in try/finally and calling MDC.remove (or MDC.clear), or by using try (MDC.MDCCloseable c = MDC.putCloseable("requestId", id)) so the key is removed automatically.
Exercise
Your handler sets requestId in MDC and then calls executor.submit(() -> log.info("done")). The line prints "[none]" for requestId. Why, and how do you fix it?
Show answer
The worker thread has its own MDC map, which starts empty, and Logback does not copy the submitting thread's map into it. Capture MDC.getCopyOfContextMap() on the submitting thread, call MDC.setContextMap on the worker before running the task, and restore or clear the worker's map in a finally block. Wrapping the executor, as MdcExecutor does, applies this to every task.
Exercise
What does %X{userId:-anonymous} print when no userId key is set in MDC for the current thread?
Show answer
It prints "anonymous". The text after ":-" is the default Logback uses when the key is missing. Without the default, the pattern would print an empty string.