Java / log4j
What is MDC object in slf4j?
MDC stands for Mapped Diagnostic Context, a feature within the SLF4J (Simple Logging Facade for Java) API that allows developers to enrich log messages with contextual information. It is particularly useful in multi-threaded applications and distributed systems for tracing specific requests or user actions across various components.
Key Concepts
-
Thread-Local Storage:
MDC works by associating key-value pairs (strings) with the current threads
execution context, similar to a
ThreadLocalvariable. All log statements made by that thread automatically include the stored MDC information. -
Abstraction Layer:
SLF4J provides a generic MDC class
(
org.slf4j.MDC) which acts as an API. It delegates the actual storage and retrieval of context data to the underlying logging framework (e.g., Logback or Log4j 2), provided that framework supports MDC functionality. -
Correlation:
By adding a unique identifier (such as a
requestIdoruserId) to the MDC at the beginning of a request, all subsequent log entries for that request can be correlated and easily filtered or analyzed.
Usage
The org.slf4j.MDC class provides static methods for managing the diagnostic context:
-
MDC.put(String key, String val): Puts a context value into the current threads context map. -
MDC.get(String key): Gets the context value identified by the key. -
MDC.remove(String key): Removes the context identified by the key from the current threads context map. -
MDC.clear(): Clears all entries in the MDC for the current thread.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
