Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What are 'nested diagnostic context' and 'mapped diagnostic context'?

 
Nam Ha Minh
Ranch Hand
Posts: 502
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read these two terms in Log4j documentation.
Could any one please explain what are they?

Many thanks.
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use Log4J's NDC class to add contextual information to the logging output of a particular thread, which you can output using the %x option of an appender's PatternLayout configuration. In a multi-threaded environment the loging output of different theads will inevitably end up as an unordered mess, and while outputting the thread name with the %t option helps, sometimes more information is needed. This is especially true when using pooled threads. The NDC basically maintains a thread local stack on which you can push bits of information about a particualar execution context as soon as you enter it, and from which you should pop that information as soon as you leave the context. An execution context is whatever you need it to be, it could simply be a method, it could span multiple methods, or it could be a part of a method.

The MDC class serves the exact same purpose, but it uses a thread local map, as opposed to a stack to track the contextual information.

 
Nam Ha Minh
Ranch Hand
Posts: 502
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks man!

I am not sure I fully understand.

Do you have examples ? How do I set the "context" for a particular thread?
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's faily straightforward, suppose the doSomething() method is invoked frequently from multiple threads:


Everytime you write to a Logger in between those NDC.push() and NDC.pop() calls, the identifier for the Foo object will be part of the logging output, assuming you're using the appropriate PatternLayout.
The reason it's surrounded by a try..finally is to make sure that the context information in the log file will always be correct, even if the code inbetween NDC.push() and NDC.pop() throws an exception.
Also note that if the doSomething() method were the first call to push() within scope of a thread's run() method, the finally block should not call NDC.pop(), but NDC.remove() instead.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic