public static class NDC extends Object
A Nested Diagnostic Context, or NDC in short, is an instrument to distinguish interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously.
Interleaved log output can still be meaningful if each log entry from different contexts had a distinctive stamp. This is where NDCs come into play.
Note that NDCs are managed on a per thread
basis. NDC operations such as push, #pop, #clear, #getDepth and #setMaxDepth
affect the NDC of the current thread only. NDCs of other
threads remain unaffected.
For example, a servlet can build a per client request NDC
consisting the clients host name and other information contained in
the the request. Cookies are another source of distinctive
information. To build an NDC one uses the push
operation. Simply put,
NDC.push. As a
side effect, if there is no nested diagnostic context for the
current thread, this method will create it.
NDC.pop.
NDC.remove().
There is no penalty for forgetting to match each
push operation with a corresponding pop,
except the obvious mismatch between the real application context
and the context set in the NDC.
If configured to do so, PatternLayout and TTCCLayout instances automatically retrieve the nested diagnostic
context for the current thread without any user intervention.
Hence, even if a servlet is serving multiple clients
simultaneously, the logs emanating from the same code (belonging to
the same category) can still be distinguished because each client
request will have a different NDC tag.
Heavy duty systems should call the #remove method when
leaving the run method of a thread. This ensures that the memory
used by the thread can be freed by the Java garbage
collector. There is a mechanism to lazily remove references to dead
threads. In practice, this means that you can be a little sloppy
and sometimes forget to call #remove before exiting a
thread.
A thread may inherit the nested diagnostic context of another
(possibly parent) thread using the inherit
method. A thread may obtain a copy of its NDC with the cloneStack method and pass the reference to any other
thread, in particular to a child.
Copyright © 2021 JBoss by Red Hat. All rights reserved.