Sub topic 11
Adding request context with MDC
This chapter assumes you can write log statements with SLF4J, set a console pattern in application.properties, and register a servlet filter in a Spring MVC application. It builds on the log pattern chapter, because MDC values only appear in output when the pattern asks for them.
The problem: interleaved log lines
A web application handles many requests at once, each on its own thread. Their log lines are mixed in one file:
10:15:01.120 INFO OrderService - Placing order A-17 with 3 items
10:15:01.121 INFO OrderService - Placing order B-02 with 1 items
10:15:01.134 ERROR OrderService - Payment declinedWhich request produced the error? You could add the order ID to every message, but that is repetitive and easy to forget. Some code, such as a library or a shared helper, does not know the order ID at all.
What MDC is
The Mapped Diagnostic Context (MDC) is a map of string keys to string values that is attached to the current thread. The map is part of SLF4J, and Logback implements it. You put a value in once. Every log statement made on that thread afterwards can include the value through the pattern, without the code passing it around.
The API is small:
| Method | Purpose |
|---|---|
| `MDC.put(key, value)` | Set a value for the current thread |
| `MDC.get(key)` | Read a value |
| `MDC.remove(key)` | Remove one key |
| `MDC.clear()` | Remove all keys on this thread |
| `MDC.getCopyOfContextMap()` | Snapshot the map, or `null` if it is empty |
| `MDC.setContextMap(map)` | Replace the whole map |
| `MDC.putCloseable(key, value)` | Set a value that is removed when a try-with-resources block ends |
Setting the context in a filter
The right place to start a request's context is a servlet filter, because it wraps everything else that happens in the request. The filter below reuses an incoming X-Request-Id header when a caller or gateway supplied one. Otherwise it generates an ID. It also returns the ID to the client, so a user can quote it in a bug report.
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
private static final String HEADER = "X-Request-Id";
private static final String KEY = "requestId";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String id = request.getHeader(HEADER);
if (id == null || id.isBlank() || id.length() > 64) {
id = UUID.randomUUID().toString();
}
MDC.put(KEY, id);
response.setHeader(HEADER, id);
try {
chain.doFilter(request, response);
} finally {
MDC.remove(KEY);
}
}
}Three details matter here.
@Order(Ordered.HIGHEST_PRECEDENCE)makes this filter run before other filters, so their log lines also carry the ID.- The length check guards against a client sending a huge or hostile header value that would end up in every log line. Also consider rejecting values with newlines or control characters, which could forge log entries. A strict pattern such as letters, digits, and dashes is safest.
- The
finallyblock is not optional. See the next section.
Why cleanup matters
Servlet containers reuse threads from a pool. If you set an MDC value and never remove it, the next request that lands on that thread starts with the previous request's ID. The result is worse than a missing ID: logs that point you at the wrong request.
The diagram below shows the lifecycle of one request.
Showing the value in the pattern
MDC values are invisible until the pattern refers to them. Use %X{key}:
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%X{requestId:-no-request}] %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{requestId:-no-request}] %logger{36} - %msg%nThe :-no-request part is a default. Without it, a log line written outside a request, such as at startup or from a scheduled job, prints an empty value, or []. A visible default makes it clear the line had no request context, instead of looking like a bug in the pattern.
Output now looks like this:
10:15:01.120 INFO [3f2a9c1e-7b1d-4c55-9d0e-1a2b3c4d5e6f] c.e.orders.OrderService - Placing order A-17 with 3 items
10:15:01.121 INFO [9d8e7f60-aa11-42b3-8c77-55e1f0a9b2c4] c.e.orders.OrderService - Placing order B-02 with 1 itemsYou can now filter a file with grep 3f2a9c1e and see one request from start to finish.
Scoped values with try-with-resources
For context that applies to a smaller scope than a whole request, such as one item in a batch job, putCloseable removes the key for you:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
@Component
public class InvoiceBatch {
private static final Logger log = LoggerFactory.getLogger(InvoiceBatch.class);
public void run(Iterable<String> customerIds) {
for (String customerId : customerIds) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("customerId", customerId)) {
log.info("Generating invoice");
// work for this customer
}
}
}
}Reference %X{customerId} in the pattern and each line inside the block carries it.
Threads you do not control
The MDC is stored per thread. When work moves to another thread, the new thread does not see the map. This happens with @Async, CompletableFuture.supplyAsync, executor services, and scheduled tasks. Log lines from that work show your default value or an empty field.
Spring's TaskDecorator hook solves this for executors that Spring manages. It wraps each task: capture the map on the submitting thread, install it on the worker thread, and restore the worker's previous state afterwards.
import java.util.Map;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public TaskDecorator mdcTaskDecorator() {
return runnable -> {
Map<String, String> captured = MDC.getCopyOfContextMap();
return () -> {
Map<String, String> previous = MDC.getCopyOfContextMap();
try {
if (captured != null) {
MDC.setContextMap(captured);
} else {
MDC.clear();
}
runnable.run();
} finally {
if (previous != null) {
MDC.setContextMap(previous);
} else {
MDC.clear();
}
}
};
};
}
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor(TaskDecorator mdcTaskDecorator) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(8);
executor.setThreadNamePrefix("async-");
executor.setTaskDecorator(mdcTaskDecorator);
executor.initialize();
return executor;
}
}Beans named taskExecutor are what @Async uses by default. Plain java.util.concurrent pools that you create yourself need the same wrapping done by hand.
Cases where thread-bound MDC does not work
- Reactive code (WebFlux, Reactor): one request hops between threads, so the thread-local MDC is unreliable. Use Reactor's context and the Micrometer context-propagation library instead.
- Virtual threads: each task still has its own thread, so the filter pattern works. Context does not flow to child tasks automatically, so the same copy-and-restore rule applies.
- Request-end logging: access-log or error-handler code that runs after your filter's
finallyblock will not see the ID. Log that line inside the filter if you need it.
Tracing and correlation IDs
If your application uses Micrometer Tracing, the tracer puts traceId and spanId into the MDC for you. Spring Boot 3.2 and later has a logging.pattern.correlation property that adds them to the default pattern. In that case you may not need your own requestId, and a hand-written filter would duplicate that work. Check what your tracing setup already provides before adding one.
Common errors
| Symptom | Likely cause |
|---|---|
| Value is always empty in logs | The pattern lacks `%X{key}`, or the key spelling differs from `MDC.put` |
| Logs show another request's ID | The value was never removed, and a pooled thread was reused |
| ID missing in `@Async` methods | The executor has no `TaskDecorator` |
| Lines before the controller lack the ID | The filter's order is too late in the chain |
| Values with line breaks split log entries | Untrusted input was put in the MDC without validation |
Exercise
A teammate sets MDC.put("userId", user.getId()) in a controller method but never removes it. Two days later, a log line for an anonymous request shows a user ID. Explain why, and give two fixes.
Show answer
The servlet container reuses threads from a pool. The MDC is stored on the thread, so the old userId stays after the first request ends and appears on whatever request next runs on that thread. Fix one: wrap the work in try/finally and call MDC.remove("userId") in the finally block. Fix two: set the value in a filter that always cleans up, or use try (MDC.MDCCloseable c = MDC.putCloseable("userId", id)) so the key is removed automatically.
Exercise
Your service method annotated with @Async logs "[no-request]" even though the calling controller logs a real request ID. What is missing, and what must the fix do on the worker thread?
Show answer
The MDC does not cross threads, so the worker thread has an empty map. Register a TaskDecorator on the executor. It must capture MDC.getCopyOfContextMap() on the submitting thread, call MDC.setContextMap on the worker thread before running the task, and restore the previous map (or clear it) in a finally block afterwards.