Package cloud.opencode.base.log.context
package cloud.opencode.base.log.context
Log Context - MDC and NDC Context Management
日志上下文 - MDC 和 NDC 上下文管理
This package provides thread-local context management for enriching log messages with contextual information like trace IDs, user IDs, etc.
本包提供线程本地上下文管理,用于通过追踪 ID、用户 ID 等上下文信息丰富日志消息。
Key Classes | 核心类
MDC- Mapped Diagnostic Context (key-value)NDC- Nested Diagnostic Context (stack-based)LogContext- Unified context management
MDC Usage | MDC 使用
// Basic usage
MDC.put("traceId", "abc-123");
MDC.put("userId", "user456");
log.info("Processing request"); // Will include traceId and userId
MDC.clear();
// AutoCloseable scope (recommended)
try (var scope = MDC.scope("requestId", requestId)) {
processRequest();
} // Automatically cleaned up
// Lambda execution
MDC.runWith(Map.of("key", "value"), () -> {
// MDC context active here
});
NDC Usage | NDC 使用
NDC.push("entering method A");
NDC.push("processing item X");
log.debug("Current operation"); // Stack: [entering method A, processing item X]
NDC.pop();
NDC.pop();
// AutoCloseable scope
try (var scope = NDC.scope("operation-name")) {
performOperation();
}
LogContext for Standard Keys | LogContext 标准键
LogContext.setTraceId("trace-123");
LogContext.setUserId("user-456");
LogContext.setTenantId("tenant-789");
// Async context propagation
ContextSnapshot snapshot = LogContext.capture();
executor.submit(() -> snapshot.runWith(() -> {
// MDC context restored here
}));
- Since:
- JDK 25, opencode-base-log V1.0.0
- Author:
- OpenCode Cloud Group
- See Also:
-
ClassesClassDescriptionLog Context - Unified Context Management 日志上下文 - 统一上下文管理Context Snapshot - Immutable snapshot for async propagation.MDC - Mapped Diagnostic Context MDC - 映射诊断上下文MDC Scope - AutoCloseable for automatic cleanup.NDC - Nested Diagnostic Context NDC - 嵌套诊断上下文NDC Scope - AutoCloseable for automatic pop.