Logging with Context: A Deep Dive into org.slf4j.MDC in Spring Boot

Anil R
1 min readNov 19, 2024

--

org.slf4j.MDC stands for Mapped Diagnostic Context, which is part of the SLF4J (Simple Logging Facade for Java) library. It is a logging feature that provides a way to enrich log messages with additional contextual information that can be useful for troubleshooting and analysis, especially in multi-threaded and distributed environments.

Key Features

  1. Thread-local Context:
  • MDC uses a thread-local map to store contextual data.
  • Each thread has its own MDC, ensuring thread safety.
  • The context is automatically inherited by child threads.

3. Key-Value Pairs:

  • MDC allows storing contextual information as key-value pairs.
  • For example, you can add a user ID, request ID, or session ID to logs to trace activities specific to a user or request.

3. Integration with Log Frameworks:

  • MDC data can be included in log messages automatically by configuring log formats in logging frameworks like Logback or Log4j.

Common Use Cases

  1. Tracing Requests: Add a unique identifier (e.g., requestId) for each request to trace logs across distributed systems.
  2. User Context: Include user-specific details like userId to identify which user triggered a particular action.
  3. Debugging Threads: Use MDC to differentiate logs from various threads during debugging.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet