Mapped Diagnostic Context (MDC)

Srikanth Dannarapu
Javarevisited
Published in
2 min readFeb 28, 2023

Mapped Diagnostic Context (MDC) is a feature in the Logback framework (which is the default logging framework for Spring Boot) that allows you to store contextual information in a logging message. The MDC is a key-value store that is propagated between logging events, so you can use it to store information such as a user ID or request ID and then include that information in every log message emitted in a single request.

Here is an example of how you could use MDC in a Spring Boot application:

  1. First, you’ll need to add the logback-classic dependency to your pom.xml:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>

2. Next, you’ll need to configure a logger in your logback.xml configuration file to include the MDC in the log messages:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %mdc - %msg%n</pattern>
</encoder>
</appender>

<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>

3. In your Spring Boot application, you can use the MDC to store contextual information. For example, you can store the user ID in the MDC in a RequestInterceptor:

@Component
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userId = request.getHeader("userId");
MDC.put("userId", userId);
return true;
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.remove("userId");
}
}

The purpose of the RequestInterceptor is to store the user ID in the Mapped Diagnostic Context (MDC), which is a key-value store that can be used to add contextual information to log messages.

4. Now, every log message emitted in the context of a single request will include the user ID stored in the MDC. Here’s an example log message:

14:55:55.234 [http-nio-8080-exec-2] DEBUG c.e.s.c.RequestInterceptor - {userId=abc123} - Handling request...

This is just a simple example of how you can use the MDC in a Spring Boot application. You can store any contextual information you like in the MDC and use it to provide more context in your log messages.

To actually log the user ID, you would need to add a log statement in the appropriate place in your code. For example, you could add a log statement at the beginning of a controller method:

@Controller
public class MyController {
private static final Logger LOGGER = LoggerFactory.getLogger(MyController.class);

@RequestMapping("/some-endpoint")
public ResponseEntity<String> handleRequest() {
LOGGER.debug("Handling request from user {}", MDC.get("userId"));
// ...
}
}

With the above configuration, each time the handleRequest method is called, a log message will be emitted that includes the user ID stored in the MDC.

Thanks, before you go:

  • 👏 Please clap for the story and follow the author 👉
  • Please share your questions or insights in the comments section below. Let’s help each other and become better Java developers.
  • Let’s connect on LinkedIn

--

--