Wednesday, October 26, 2011

Log4j: NDC/MDC

Nested Diagnostic Context (NDC) and Mapped Diagnostic Context (MDC) are used in cases when we want to distinguish logs from multiple threads by marking each log with thread specific information. NDC and MDC provide possibility to store some contextual information for each thread. But there's a difference in the way they do it.

Each thread has it's own context. NDC uses stack for pushing information when entering thread's context and popping it when leaving that context. This information is attached to log and can be displayed by using '%x' Pattern Layout option.

MDC uses map to store context information. It means that there must be a unique key associated with each piece of thread information. The information is attached to log and can be displayed by using '%X{key}' Pattern Layout option, where the key is an association with a value in the map.

Here you can find Log4j Pattern Layout option's description: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

No comments:

Post a Comment