Class MDC
java.lang.Object
cloud.opencode.base.log.context.MDC
MDC - Mapped Diagnostic Context
MDC - 映射诊断上下文
MDC provides a way to enrich log messages with contextual information that is specific to the current thread of execution.
MDC 提供一种方式,用当前执行线程特定的上下文信息丰富日志消息。
Example | 示例:
// Set context values
MDC.put("requestId", "req-12345");
MDC.put("userId", "user-001");
// Use scope for automatic cleanup
try (MDCScope scope = MDC.scope("orderId", "ORD-001")) {
OpenLog.info("Processing order"); // Includes orderId
}
// orderId automatically removed
// Run with context
MDC.runWith("taskId", "task-001", () -> {
OpenLog.info("Executing task");
});
Features | 主要功能:
- Thread-local mapped diagnostic context - 线程本地映射诊断上下文
- Scope-based auto-cleanup (try-with-resources) - 基于作用域的自动清理(try-with-resources)
- Temporary value binding via runWith/callWith - 通过 runWith/callWith 临时值绑定
Security | 安全性:
- Thread-safe: Yes (ThreadLocal-based) - 线程安全: 是(基于 ThreadLocal)
- Null-safe: Yes (returns null for missing keys) - 空值安全: 是(缺少的键返回 null)
- Since:
- JDK 25, opencode-base-log V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classMDC Scope - AutoCloseable for automatic cleanup. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> TExecutes a task with a temporary MDC value and returns the result.static voidclear()Clears all entries from the MDC.static StringGets a value from the MDC.Returns a copy of the current context map.static voidPuts a key-value pair into the MDC.static voidRemoves a key from the MDC.static voidExecutes a task with a temporary MDC value.static MDC.MDCScopeCreates an MDC scope for automatic cleanup.static MDC.MDCScopeCreates an MDC scope with multiple values.static voidsetContextMap(Map<String, String> contextMap) Sets the context map.
-
Method Details
-
put
-
get
-
remove
Removes a key from the MDC. 从 MDC 移除键。- Parameters:
key- the key to remove - 要移除的键
-
clear
public static void clear()Clears all entries from the MDC. 清空 MDC 中的所有条目。 -
getCopyOfContextMap
-
setContextMap
-
runWith
-
callWith
Executes a task with a temporary MDC value and returns the result. 使用临时 MDC 值执行任务并返回结果。- Type Parameters:
T- the result type - 结果类型- Parameters:
key- the key - 键value- the value - 值supplier- the task - 任务- Returns:
- the result - 结果
-
scope
Creates an MDC scope for automatic cleanup. 创建用于自动清理的 MDC 作用域。- Parameters:
key- the key - 键value- the value - 值- Returns:
- the scope - 作用域
-
scope
Creates an MDC scope with multiple values. 创建具有多个值的 MDC 作用域。- Parameters:
values- the key-value pairs - 键值对- Returns:
- the scope - 作用域
-