Simple Logging Facade for Java (SLF4J) API - a facade/abstraction layer for various logging frameworks.
MDC (Mapped Diagnostic Context) provides a thread-local storage mechanism for associating contextual information with log statements. This enables automatic inclusion of contextual data in log messages without explicitly passing it to each logging call. SLF4J 2.0 extends MDC with stack-based operations for nested contexts.
Core key-value storage operations for thread-local diagnostic context.
/**
* This class hides and serves as a substitute for the underlying logging system's MDC implementation
*/
public class MDC {
/**
* Put a diagnostic context value as identified with the key parameter into the current thread's diagnostic context map
* @param key non-null key
* @param val value to put in the map
* @throws IllegalArgumentException in case the "key" parameter is null
*/
public static void put(String key, String val) throws IllegalArgumentException;
/**
* Get the diagnostic context identified by the key parameter
* @param key a key
* @return the string value identified by the key parameter
* @throws IllegalArgumentException in case the "key" parameter is null
*/
public static String get(String key) throws IllegalArgumentException;
/**
* Remove the diagnostic context identified by the key parameter
* @param key a key
* @throws IllegalArgumentException in case the "key" parameter is null
*/
public static void remove(String key) throws IllegalArgumentException;
/**
* Clear all entries in the MDC of the underlying implementation
*/
public static void clear();
}Bulk operations for managing the entire diagnostic context.
/**
* Return a copy of the current thread's context map, with keys and values of type String
* @return A copy of the current thread's context map. May be null.
*/
public static Map<String, String> getCopyOfContextMap();
/**
* Set the current thread's context map by first clearing any existing map and then copying the map passed as parameter
* @param contextMap must contain only keys and values of type String
*/
public static void setContextMap(Map<String, String> contextMap);Automatic cleanup using try-with-resources pattern.
/**
* Put a diagnostic context value and return a Closeable that removes the key when closed
* @param key non-null key
* @param val value to put in the map
* @return a Closeable who can remove key when close is called
* @throws IllegalArgumentException in case the "key" parameter is null
*/
public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException;
/**
* An adapter to remove the key when done
*/
public static class MDCCloseable implements Closeable {
/**
* Remove the MDC key when closed
*/
public void close();
}Stack-based operations for nested diagnostic contexts.
/**
* Push a value into the deque(stack) referenced by 'key'
* @param key identifies the appropriate stack
* @param value the value to push into the stack
*/
public static void pushByKey(String key, String value);
/**
* Pop the stack referenced by 'key' and return the value possibly null
* @param key identifies the deque(stack)
* @return the value just popped. May be null
*/
public static String popByKey(String key);
/**
* Returns a copy of the deque(stack) referenced by 'key'. May be null.
* @param key identifies the stack
* @return copy of stack referenced by 'key'. May be null.
*/
public Deque<String> getCopyOfDequeByKey(String key);
/**
* Clear the deque(stack) referenced by 'key'
* @param key identifies the stack
*/
public static void clearDequeByKey(String key);Interface for underlying MDC implementations.
/**
* This interface abstracts the service offered by various MDC implementations
*/
public interface MDCAdapter {
/**
* Put a context value as identified by key into the current thread's context map
* @param key the key
* @param val the value
*/
public void put(String key, String val);
/**
* Get the context identified by the key parameter
* @param key the key
* @return the string value identified by the key
*/
public String get(String key);
/**
* Remove the the context identified by the key parameter
* @param key the key to remove
*/
public void remove(String key);
/**
* Clear all entries in the MDC
*/
public void clear();
/**
* Return a copy of the current thread's context map
* @return A copy of the current thread's context map. May be null.
*/
public Map<String, String> getCopyOfContextMap();
/**
* Set the current thread's context map by first clearing any existing map and then copying the map
* @param contextMap must contain only keys and values of type String
*/
public void setContextMap(Map<String, String> contextMap);
/**
* Push a value into the deque(stack) referenced by 'key'
* @param key identifies the appropriate stack
* @param value the value to push into the stack
*/
public void pushByKey(String key, String value);
/**
* Pop the stack referenced by 'key' and return the value possibly null
* @param key identifies the deque(stack)
* @return the value just popped. May be null
*/
public String popByKey(String key);
/**
* Returns a copy of the deque(stack) referenced by 'key'. May be null.
* @param key identifies the stack
* @return copy of stack referenced by 'key'. May be null.
*/
public Deque<String> getCopyOfDequeByKey(String key);
/**
* Clear the deque(stack) referenced by 'key'
* @param key identifies the stack
*/
public void clearDequeByKey(String key);
}Usage Examples:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.util.Map;
public class MDCExample {
private static final Logger logger = LoggerFactory.getLogger(MDCExample.class);
public void basicMDCUsage() {
// Set context information
MDC.put("userId", "user123");
MDC.put("sessionId", "session456");
MDC.put("requestId", "req789");
// All subsequent log messages will include this context
logger.info("User operation started");
logger.debug("Processing user data");
logger.info("User operation completed");
// Clean up context
MDC.clear();
}
public void autoCleanupUsage() {
// Automatic cleanup using try-with-resources
try (MDC.MDCCloseable mdcCloseable = MDC.putCloseable("transactionId", "tx123")) {
logger.info("Transaction started");
// Nested context
try (MDC.MDCCloseable orderContext = MDC.putCloseable("orderId", "order456")) {
logger.info("Processing order");
processOrder();
logger.info("Order processed successfully");
} // orderId automatically removed
logger.info("Transaction completed");
} // transactionId automatically removed
}
public void webRequestExample(String userId, String sessionId, String requestId) {
// Set request context at the beginning of request processing
MDC.put("userId", userId);
MDC.put("sessionId", sessionId);
MDC.put("requestId", requestId);
MDC.put("thread", Thread.currentThread().getName());
try {
logger.info("Processing web request");
// All log messages in the call chain will include the context
businessService.processRequest();
logger.info("Web request completed successfully");
} catch (Exception e) {
logger.error("Web request failed", e);
} finally {
// Always clean up MDC at the end of request
MDC.clear();
}
}
public void contextMapOperations() {
// Set multiple values
Map<String, String> contextMap = Map.of(
"userId", "user123",
"department", "engineering",
"role", "developer",
"location", "office-nyc"
);
MDC.setContextMap(contextMap);
logger.info("Context established");
// Get a copy of current context
Map<String, String> currentContext = MDC.getCopyOfContextMap();
logger.debug("Current context has {} entries", currentContext.size());
// Modify context
MDC.put("operation", "data-processing");
logger.info("Starting data processing");
MDC.clear();
}
}Stack operations enable nested contexts with automatic cleanup:
public class StackMDCExample {
private static final Logger logger = LoggerFactory.getLogger(StackMDCExample.class);
public void nestedOperations() {
// Push operation context onto stack
MDC.pushByKey("operation", "main-process");
logger.info("Starting main process");
try {
// Nested operation
MDC.pushByKey("operation", "sub-process-1");
logger.info("Starting sub process 1");
processData();
logger.info("Sub process 1 completed");
MDC.popByKey("operation"); // Remove sub-process-1
// Another nested operation
MDC.pushByKey("operation", "sub-process-2");
logger.info("Starting sub process 2");
processMoreData();
logger.info("Sub process 2 completed");
MDC.popByKey("operation"); // Remove sub-process-2
logger.info("Main process completed");
} finally {
MDC.popByKey("operation"); // Remove main-process
}
}
public void traceExecutionPath() {
MDC.pushByKey("trace", "serviceA");
logger.debug("Entering Service A");
try {
MDC.pushByKey("trace", "serviceB");
logger.debug("Calling Service B");
try {
MDC.pushByKey("trace", "serviceC");
logger.debug("Calling Service C");
// Process in Service C
logger.info("Processing in Service C");
logger.debug("Exiting Service C");
} finally {
MDC.popByKey("trace");
}
logger.debug("Exiting Service B");
} finally {
MDC.popByKey("trace");
}
logger.debug("Exiting Service A");
MDC.popByKey("trace");
}
public void inspectStack() {
MDC.pushByKey("context", "level1");
MDC.pushByKey("context", "level2");
MDC.pushByKey("context", "level3");
// Get copy of the current stack
Deque<String> contextStack = MDC.getCopyOfDequeByKey("context");
logger.info("Context stack size: {}", contextStack.size());
logger.info("Current context: {}", contextStack.peek());
// Clean up
while (!contextStack.isEmpty()) {
String popped = MDC.popByKey("context");
logger.debug("Popped context: {}", popped);
}
}
}@Component
public class RequestContextFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(RequestContextFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Set up request context
MDC.put("requestId", generateRequestId());
MDC.put("method", httpRequest.getMethod());
MDC.put("uri", httpRequest.getRequestURI());
MDC.put("remoteAddr", httpRequest.getRemoteAddr());
MDC.put("userAgent", httpRequest.getHeader("User-Agent"));
// Extract user info if available
String userId = extractUserId(httpRequest);
if (userId != null) {
MDC.put("userId", userId);
}
try {
logger.info("Request started");
chain.doFilter(request, response);
logger.info("Request completed");
} catch (Exception e) {
logger.error("Request failed", e);
throw e;
} finally {
// Always clean up MDC
MDC.clear();
}
}
}@Service
public class AsyncProcessingService {
private static final Logger logger = LoggerFactory.getLogger(AsyncProcessingService.class);
@Async
public CompletableFuture<String> processAsync(String data) {
// Copy context from calling thread
Map<String, String> contextMap = MDC.getCopyOfContextMap();
return CompletableFuture.supplyAsync(() -> {
// Set context in async thread
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
// Add async-specific context
MDC.put("thread", Thread.currentThread().getName());
MDC.put("asyncTask", "data-processing");
try {
logger.info("Starting async processing");
String result = performProcessing(data);
logger.info("Async processing completed");
return result;
} catch (Exception e) {
logger.error("Async processing failed", e);
throw e;
} finally {
MDC.clear();
}
});
}
}@Component
public class TransactionContextManager {
private static final Logger logger = LoggerFactory.getLogger(TransactionContextManager.class);
@EventListener
public void handleTransactionBegin(TransactionBeginEvent event) {
String transactionId = event.getTransactionId();
MDC.put("transactionId", transactionId);
MDC.put("transactionStatus", "ACTIVE");
MDC.pushByKey("transactionStack", transactionId);
logger.info("Transaction started");
}
@EventListener
public void handleTransactionCommit(TransactionCommitEvent event) {
MDC.put("transactionStatus", "COMMITTED");
logger.info("Transaction committed");
MDC.popByKey("transactionStack");
cleanupTransactionContext();
}
@EventListener
public void handleTransactionRollback(TransactionRollbackEvent event) {
MDC.put("transactionStatus", "ROLLED_BACK");
logger.warn("Transaction rolled back: {}", event.getCause().getMessage());
MDC.popByKey("transactionStack");
cleanupTransactionContext();
}
private void cleanupTransactionContext() {
MDC.remove("transactionId");
MDC.remove("transactionStatus");
// If no more transactions in stack, clean up completely
Deque<String> stack = MDC.getCopyOfDequeByKey("transactionStack");
if (stack == null || stack.isEmpty()) {
MDC.remove("transactionStack");
}
}
}@Component
public class SecurityContextManager {
private static final Logger logger = LoggerFactory.getLogger(SecurityContextManager.class);
public void setSecurityContext(Authentication authentication) {
if (authentication != null && authentication.isAuthenticated()) {
MDC.put("userId", authentication.getName());
MDC.put("userRoles", extractRoles(authentication));
MDC.put("authMethod", authentication.getClass().getSimpleName());
if (authentication.getDetails() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
MDC.put("remoteAddress", details.getRemoteAddress());
MDC.put("sessionId", details.getSessionId());
}
logger.debug("Security context established");
} else {
MDC.put("userId", "anonymous");
MDC.put("userRoles", "none");
logger.debug("Anonymous security context established");
}
}
public void clearSecurityContext() {
MDC.remove("userId");
MDC.remove("userRoles");
MDC.remove("authMethod");
MDC.remove("remoteAddress");
MDC.remove("sessionId");
logger.debug("Security context cleared");
}
}public class MDCKeys {
// Request context
public static final String REQUEST_ID = "requestId";
public static final String SESSION_ID = "sessionId";
public static final String USER_ID = "userId";
// Business context
public static final String TRANSACTION_ID = "transactionId";
public static final String ORDER_ID = "orderId";
public static final String CUSTOMER_ID = "customerId";
// Technical context
public static final String THREAD_NAME = "thread";
public static final String OPERATION = "operation";
public static final String COMPONENT = "component";
}// Good: Simple string values
MDC.put("userId", user.getId());
MDC.put("orderTotal", order.getTotal().toString());
// Avoid: Expensive operations
// MDC.put("userProfile", expensiveUserProfileSerialization(user));
// Good: Conditional population
if (logger.isDebugEnabled()) {
MDC.put("debugInfo", generateDebugInformation());
}Install with Tessl CLI
npx tessl i tessl/maven-org-slf4j--slf4j-api