当使用“嵌套诊断上下文”(NDC)?嵌套、上下文、NDC

2023-09-02 10:43:19 作者:只剩下废墟

与log4net的演奏,我见过使用每线程栈的背景下标签名为NDC的可能性。

Playing with log4net, I have seen the possibility to use a per-thread stack of context labels called the NDC.

标签压在这堆被显示在的PatternLayout通过指定%X %NDC 格式参数。

The labels pushed on this stack are displayed in a PatternLayout by specifying the %x or the %ndc format parameter.

的用法是这样的:

ILog log = log4net.LogManager.GetLogger(...) ;

//pattern layout format: "[%ndc] - %message%newline"

log.Info("message 1"); 
using(log4net.NDC.Push("context")
{
    using(log4net.NDC.Push("inner_context")
    {
      log.Info("message 2"); 
    }
    log.Info("message 3"); 
}
log.Info("message 4");

输出结果是这样的:

The output is something like:

null - message 1
context inner_context - message 2
context - message 3
null - message 4

在您的编程经验与log4net的,你什么时候发现这个功能是有用的?

In your programming experience with log4net, when did you find this feature to be useful?

推荐答案

在服务器应用程序如ASP.NET。

In a server application such as ASP.NET.

例如,你可以把有关的NDC当前请求的信息。

For example, you can push information about the current request on to the NDC.