Class NDC

java.lang.Object
cloud.opencode.base.log.context.NDC

public final class NDC extends Object
NDC - Nested Diagnostic Context NDC - 嵌套诊断上下文

NDC provides a stack-based context for enriching log messages. It is useful for tracking nested operations or call stacks.

NDC 提供基于栈的上下文来丰富日志消息。它对于跟踪嵌套操作或调用栈很有用。

Example | 示例:

NDC.push("enter processOrder");
try {
    NDC.push("validate order");
    // validation
    NDC.pop();

    NDC.push("save order");
    // save
    NDC.pop();
} finally {
    NDC.pop();
}

// Use scope for automatic cleanup
try (NDCScope scope = NDC.scope("processPayment")) {
    OpenLog.info("Processing payment");
}

Features | 主要功能:

  • Stack-based nested diagnostic context - 基于栈的嵌套诊断上下文
  • Scope-based auto-cleanup (try-with-resources) - 基于作用域的自动清理(try-with-resources)
  • Configurable maximum stack depth - 可配置的最大栈深度

Security | 安全性:

  • Thread-safe: Yes (ThreadLocal-based) - 线程安全: 是(基于 ThreadLocal)
  • Null-safe: Yes (returns null when empty) - 空值安全: 是(为空时返回 null)
Since:
JDK 25, opencode-base-log V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • push

      public static void push(String message)
      Pushes a message onto the NDC stack. 将消息推入 NDC 栈。
      Parameters:
      message - the message to push - 要推入的消息
    • pop

      public static String pop()
      Pops the top message from the NDC stack. 从 NDC 栈弹出顶部消息。
      Returns:
      the popped message, or null if empty - 弹出的消息,如果为空则返回 null
    • peek

      public static String peek()
      Returns the top message without removing it. 返回顶部消息但不移除它。
      Returns:
      the top message, or null if empty - 顶部消息,如果为空则返回 null
    • clear

      public static void clear()
      Clears the NDC stack. 清空 NDC 栈。
    • getDepth

      public static int getDepth()
      Returns the depth of the NDC stack. 返回 NDC 栈的深度。
      Returns:
      the stack depth - 栈深度
    • setMaxDepth

      public static void setMaxDepth(int maxDepth)
      Sets the maximum depth of the NDC stack. 设置 NDC 栈的最大深度。
      Parameters:
      maxDepth - the maximum depth - 最大深度
    • getCopyOfStack

      public static Deque<String> getCopyOfStack()
      Returns a copy of the NDC stack. 返回 NDC 栈的副本。
      Returns:
      a copy of the stack - 栈的副本
    • setStack

      public static void setStack(Deque<String> stack)
      Sets the NDC stack. 设置 NDC 栈。
      Parameters:
      stack - the stack to set - 要设置的栈
    • scope

      public static NDC.NDCScope scope(String message)
      Creates an NDC scope for automatic cleanup. 创建用于自动清理的 NDC 作用域。
      Parameters:
      message - the message to push - 要推入的消息
      Returns:
      the scope - 作用域