Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Structured Logging with MDC | Practical Logging in Spring Boot
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Logging and Monitoring in Spring Applications

bookStructured Logging with MDC

Structured logging is essential in Spring Boot applications for making log data easy to search, filter, and analyze. By organizing log entries in a consistent format, you can quickly identify issues, trace requests, and monitor application behavior across distributed systems. The Mapped Diagnostic Context (MDC) is a powerful tool that allows you to enrich your logs with context-specific information, such as user IDs, session tokens, or request identifiers. Using MDC, you can automatically include these details in every log message, making your logs far more valuable for debugging and monitoring.

What Is MDC (Mapped Diagnostic Context)?

Mapped Diagnostic Context (MDC) is a feature provided by many logging frameworks, including those commonly used with Spring Boot, such as Logback and Log4j2. MDC lets you attach contextual information—like user IDs, request IDs, or session data—to your log entries. This context is stored in a thread-local map, so every log message generated in that thread can include the additional details automatically.

Why Use MDC for Structured Logging?

Structured logging means adding meaningful context to your logs in a consistent, machine-readable way. With MDC, you can:

  • Add identifiers (such as userId or requestId) to every log message in a request;
  • Improve traceability by making it easier to track actions across services and threads;
  • Simplify debugging and monitoring in distributed or multi-user applications.

Using MDC in Spring Boot

You can use MDC in your Spring Boot application by interacting with the org.slf4j.MDC class. Here’s how you can add contextual information to your logs:

Adding Context to Logs

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/users/{id}")
    public String getUser(@PathVariable String id) {
        MDC.put("userId", id); // Add userId to the logging context
        logger.info("Fetching user details");
        // ... fetch user logic ...
        MDC.clear(); // Always clear context after use
        return "User details for " + id;
    }
}

With this setup, every log entry inside getUser will include the userId value, as long as your log pattern references it (for example, %X{userId} in Logback configuration).

How MDC Improves Log Traceability

Suppose multiple users are making requests at the same time. Without MDC, your logs will mix together, making it hard to know which entry belongs to which user. By using MDC, you can filter and search logs for a specific userId or requestId, making it much easier to trace the flow of a single request.

Example log output with MDC:

2024-06-01 10:15:30 INFO  [userId=12345] Fetching user details

This approach helps you:

  • Quickly pinpoint issues for a single user or request;
  • Understand the sequence of actions for a specific context;
  • Simplify troubleshooting in complex Spring Boot applications.

Always remember to clear the MDC context after the request is handled to avoid leaking information between threads.

question mark

Which feature allows you to add contextual information, such as user IDs or request IDs, to your log entries in a Spring Boot application?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

bookStructured Logging with MDC

Swipe um das Menü anzuzeigen

Structured logging is essential in Spring Boot applications for making log data easy to search, filter, and analyze. By organizing log entries in a consistent format, you can quickly identify issues, trace requests, and monitor application behavior across distributed systems. The Mapped Diagnostic Context (MDC) is a powerful tool that allows you to enrich your logs with context-specific information, such as user IDs, session tokens, or request identifiers. Using MDC, you can automatically include these details in every log message, making your logs far more valuable for debugging and monitoring.

What Is MDC (Mapped Diagnostic Context)?

Mapped Diagnostic Context (MDC) is a feature provided by many logging frameworks, including those commonly used with Spring Boot, such as Logback and Log4j2. MDC lets you attach contextual information—like user IDs, request IDs, or session data—to your log entries. This context is stored in a thread-local map, so every log message generated in that thread can include the additional details automatically.

Why Use MDC for Structured Logging?

Structured logging means adding meaningful context to your logs in a consistent, machine-readable way. With MDC, you can:

  • Add identifiers (such as userId or requestId) to every log message in a request;
  • Improve traceability by making it easier to track actions across services and threads;
  • Simplify debugging and monitoring in distributed or multi-user applications.

Using MDC in Spring Boot

You can use MDC in your Spring Boot application by interacting with the org.slf4j.MDC class. Here’s how you can add contextual information to your logs:

Adding Context to Logs

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/users/{id}")
    public String getUser(@PathVariable String id) {
        MDC.put("userId", id); // Add userId to the logging context
        logger.info("Fetching user details");
        // ... fetch user logic ...
        MDC.clear(); // Always clear context after use
        return "User details for " + id;
    }
}

With this setup, every log entry inside getUser will include the userId value, as long as your log pattern references it (for example, %X{userId} in Logback configuration).

How MDC Improves Log Traceability

Suppose multiple users are making requests at the same time. Without MDC, your logs will mix together, making it hard to know which entry belongs to which user. By using MDC, you can filter and search logs for a specific userId or requestId, making it much easier to trace the flow of a single request.

Example log output with MDC:

2024-06-01 10:15:30 INFO  [userId=12345] Fetching user details

This approach helps you:

  • Quickly pinpoint issues for a single user or request;
  • Understand the sequence of actions for a specific context;
  • Simplify troubleshooting in complex Spring Boot applications.

Always remember to clear the MDC context after the request is handled to avoid leaking information between threads.

question mark

Which feature allows you to add contextual information, such as user IDs or request IDs, to your log entries in a Spring Boot application?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 3
some-alt