Video in progress
What is the MDC and how does it work for adding context to logs?
The MDC (Mapped Diagnostic Context) is a key-value map bound to the current thread. If you put a requestId or userId in it, every log line on that thread automatically gets those values through the pattern or the JSON encoder.
📖 Answer
Adding userId by hand to every log.info is inconvenient and gets forgotten. With the MDC you set it once, at the start of the request:
@Component
public class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Request-Id"))
.orElse(UUID.randomUUID().toString());
MDC.put("requestId", id);
try {
chain.doFilter(req, res);
} finally {
MDC.remove("requestId"); // required
}
}
}
In the Logback pattern:
%d %-5level [%X{requestId}] %logger{36} - %msg%n
Now the log everywhere (controller, service, repository) has the requestId, with no code changes.
The MDC works on a ThreadLocal. Two consequences follow: the value doesn't pass to another thread (for example @Async) on its own, and if it isn't cleaned in finally, it is "inherited" by the next request on that thread pool thread.
If Micrometer Tracing is connected, the traceId and spanId land in the MDC by themselves.
Sign up to mark studied questions and save your progress.