aspose file tools*
The moose likes IDEs, Version Control and other tools and the fly likes What are 'nested diagnostic context' and 'mapped diagnostic context'? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » IDEs, Version Control and other tools
Bookmark "What are Watch "What are New topic
Author

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

Nam Ha Minh
Ranch Hand

Joined: Oct 31, 2011
Posts: 498

I read these two terms in Log4j documentation.
Could any one please explain what are they?

Many thanks.


PM Me If You Want to get Urgent Help on Java Programming
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1821
    
    7

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.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Nam Ha Minh
Ranch Hand

Joined: Oct 31, 2011
Posts: 498

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

Joined: Mar 10, 2008
Posts: 1821
    
    7

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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What are 'nested diagnostic context' and 'mapped diagnostic context'?