views:

2251

answers:

2

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

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

The usage is something like:

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

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

+3  A: 

These feature come in handy when you have lots of logs to go through. When would you have lots of logs? Diagnosing weird bug on a production system with interleaving outputs. Having more contexts gives you way to filter the output or not outputting unneeded logs.

Another case nested contexts could be useful is if a method or some feature is called several times in different contexts and you need a way to distinguish between them.

eed3si9n
+4  A: 

In a server application such as ASP.NET.

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

Joe