Sub topic 11
Adding request context with MDC
This chapter assumes you can write SLF4J log statements and set a console pattern in application.properties. You should also know what a servlet filter is.
The problem: interleaved log lines
A web application handles many requests at once. Their log lines interleave in the output, so you can't tell which lines belong to which request:
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.140 ERROR OrderService - Payment declinedThe error line doesn't say which order failed. You could add the ID to every message by hand, but then every call needs access to it.
What MDC is
The Mapped Diagnostic Context (MDC) is a map of string keys and values that SLF4J keeps for the current thread. You put a value in once. The logging backend can then print it on every line that thread writes, without any change to the log statements.
Because the map is tied to the thread, each request gets its own values as long as one thread handles one request.
Step 1: Put a value in a filter
A servlet filter runs once per request, so it is the natural place to set the context:
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.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
MDC.put("requestId", UUID.randomUUID().toString());
try {
chain.doFilter(request, response);
} finally {
MDC.remove("requestId");
}
}
}The finally block matters. Servlet containers reuse threads from a pool. If you skip the cleanup, the next request on that thread logs the previous request's ID.
Step 2: Print it in the pattern
Reference the key with %X{key}:
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%X{requestId}] %logger{36} - %msg%nEach line now carries the ID:
10:15:01.120 INFO [3f9c...] OrderService - Placing order A-17 with 3 items
10:15:01.140 ERROR [8a21...] OrderService - Payment declinedYou can search the log for one ID and see that request's whole story. If a key is missing, Logback prints an empty value. Logback also accepts a default, as in %X{requestId:-none}.
Common errors
- Missing cleanup. Without
MDC.removeorMDC.clearin afinallyblock, values leak between requests on pooled threads. - Context lost on other threads. MDC does not follow work handed to another thread, for example with
@Asyncor an executor. Log lines from that work show an empty value. - Unexpected empty values. Check the key spelling.
%X{requestid}and%X{requestId}are different keys.
To carry the context into async work, copy the map when the task is submitted:
import java.util.Map;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
public class MdcTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
Map<String, String> context = MDC.getCopyOfContextMap();
return () -> {
try {
if (context != null) {
MDC.setContextMap(context);
}
runnable.run();
} finally {
MDC.clear();
}
};
}
}Register it on your ThreadPoolTaskExecutor with setTaskDecorator(new MdcTaskDecorator()).
Exercise
A request ID appears in log lines written by the request thread, but lines written by an @Async method show an empty value. Why, and how do you fix it?
Show answer
MDC is stored per thread, and @Async runs the method on a different executor thread that never received the map. Fix it by copying the context when the task is submitted, for example with a TaskDecorator that calls MDC.getCopyOfContextMap() and MDC.setContextMap(...) inside the wrapped Runnable, then clears the MDC in a finally block.