Tip of the day #65: Use MDC for Contextualized Logging
Mapped Diagnostic Context (MDC) is a powerful tool for adding context to your log entries, making them more meaningful and easier to trace in distributed systems or complex applications. Here's how you can implement it in a Spring Boot application using SLF4J and Logback:
Example Implementation:
Adding MDC to a Web Request:
Use an interceptor or filter to add contextual information (e.g., request ID, user ID) to the MDC:
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
@Component
public class MdcFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
// Add request ID to MDC
MDC.put("requestId", UUID.randomUUID().toString());
// Optionally add user information or other context
String userId = request.getHeader("X-User-Id");
if (userId != null) {
MDC.put("userId", userId);
}
filterChain.doFilter(request, response);
} finally {
MDC.clear(); // Clean up MDC after request is processed
}
}
}
Logback Configuration:
Update your
logback.xmlto include MDC values in your log pattern:
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%X{requestId}] [%X{userId}] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>Result: Your logs will now contain contextual information, such as:
2024-12-03 14:23:45 [9f3e2a7c-f4d6-4c69-a4f2-4d8e2e18b1a2] [user123] INFO com.example.Service - Processing requestWith this you:
Improved Traceability: Easily correlate logs across microservices or threads.
Better Debugging: Add critical information like user IDs, transaction IDs, or other metadata.
Readability: Simplifies log analysis by adding meaningful context.
Do you use MDC in your project? Let me know!
Happy coding!


When will the next tip be posted