Spring Boot Logging with MDC: The Key to End-to-End Request Tracing

Modern applications, especially microservices, rely heavily on logs to troubleshoot issues. But traditional logs often fail to provide context. When a single request travels through multiple services, threads, async calls, and external APIs, it becomes nearly impossible to trace the full flow from start to end.

This is where MDC (Mapped Diagnostic Context) becomes a game-changer.

In this blog, we’ll break down:

  1. What MDC is
  2. Why MDC is needed
  3. How MDC improves logging in microservices
  4. A real-world Spring Boot example with correlation ID
  5. Best practices for production

What is MDC?

MDC (Mapped Diagnostic Context) is a logging feature (in SLF4J, Logback, Log4j2) that stores key-value pairs for the current thread.

These values automatically appear in every log entry — without you manually passing them around.

This gives you context-rich, traceable, and actionable logs.


Why Do We Need MDC? (The Real Need)

🔹 1. Track a Request Across Multiple Microservices

In real distributed systems, one client request may hit:

  • API Gateway
  • Service A
  • Service B
  • Database
  • External payment API
  • Notification service

Using MDC, you assign a correlationId once and then trace it across:

Service A → Service B → Payment API → DB → Notification

This solves the biggest challenge in microservices:

"Which logs belong to the same request?"


🔹 2. No Need to Add IDs Manually in Each Log Statement

Traditional approach:

log.info("Creating order, requestId={}", requestId);

With MDC:

MDC.put("requestId", reqId);


Now every log automatically contains the requestId:

INFO [requestId=ab12c] Order created

INFO [requestId=ab12c] Payment initiated

INFO [requestId=ab12c] Notification sent


🔹 3. Makes Production Debugging Easy

  • When an error occurs, MDC helps answer:
  • Which user triggered it?
  • Which API caused the failure?
  • What sequence of events led to the exception?


It saves hours of debugging time.


🔹 4. Works Perfectly with Log Aggregation Tools

Tools like:

  • Elastic Stack (ELK)
  • Splunk
  • Datadog
  • Grafana Loki
  • New Relic


use MDC keys such as:

  • correlationId
  • userId
  • tenantId

…to visualize flows across systems.


Without MDC, distributed tracing collapses.


🔹 5. Critical for Asynchronous and Multithreaded Systems

Spring Boot applications use:

  • @Async
  • WebClient
  • Reactor threads
  • Kafka listeners
  • Scheduled tasks


MDC ensures context flows across threads (with proper configuration).


Real-World Example: Adding a Correlation ID Using MDC in Spring Boot

Let’s walk through a production-like scenario.

Problem:

A request comes to your Order Service. You want to trace the entire flow:


1. Order created

2. Payment initiated

3. Invoice generated

4. Confirmation email sent


To correlate logs, add a correlationId to MDC.


Step 1: Create a Filter to Add Correlation ID

@Component

public class CorrelationIdFilter implements Filter {


    @Override

    public void doFilter(ServletRequest request, ServletResponse response,

                         FilterChain chain) throws IOException, ServletException {


        String correlationId = UUID.randomUUID().toString();


        MDC.put("correlationId", correlationId);


        try {

            chain.doFilter(request, response);

        } finally {

            MDC.clear();

        }

    }

}


Step 2: Include Correlation ID in Logging Pattern

Modify logback-spring.xml:

<pattern>%d %-5level [%X{correlationId}] %logger - %msg%n</pattern>


Step 3: Every Log Now Has Request Context Automatically

2025-02-12 09:45:02 INFO  [c1ab-7f22] OrderService - Order created

2025-02-12 09:45:03 INFO  [c1ab-7f22] PaymentService - Payment initiated

2025-02-12 09:45:03 INFO  [c1ab-7f22] InvoiceService - Invoice generated


Even if the request jumps across services, you can track:

  • The entire end-to-end journey
  • How long each step took
  • Which component failed


This is the biggest strength of MDC in real production systems.


Best Practices for MDC in Spring Boot

  • Always clear MDC in finally block
  • Use correlation ID from header if available (for downstream services)
  • Use UUID for uniqueness
  • Propagate MDC for async tasks
  • Add userId, tenantId only when safe
  • Do not log sensitive data


Final Thoughts

MDC is not just a logging feature—it’s a critical debugging and observability tool in modern Spring Boot microservices. It ensures every log line carries meaningful context, helping teams quickly trace problems across services and threads.

With MDC + correlation ID, your logs go from random, isolated messages to structured, traceable event flows

This drastically improves monitoring, debugging, alerting, and operational visibility.

Post a Comment

0 Comments