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?
Best Solution
Want an example?
Take the following Web API written using ASP.NET MVC4:
When server concurrent HTTP Requests are made, the logging can get interleaved. E.g.
In this simple example, you could use the thread id to distinguish requests, but that can get tricky as the log file grows in complexity.
A better alternative is to provide unique identifiers that group together log messages for the same request. We can update the code as to the following:
This produces a log that you can grep to see the issues associated with a specific request. E.g.