I would welcome your opinion on the proper use of the Nested Diagnostic Context (NDC) 
when logging using log4j.

As you know in a multi-threaded servlet environment, the NDC provides valuable 
contextual information to help make sense of otherwise hopelessly interleaved messages 
in the log device.  What is the correct procedure for setting up the NDC?  It seems 
like every log message must be sandwiched by a push() and a pop().  For example:

  NDC.push("something");
  log.debug("The message being logged");
  NDC.pop();

What is the overhead of changing all log statements to this format?  Especially 
requiring consideration is the fact that the "something" that uniquely identifies a 
context isn't always readily available and may require some computation to obtain.  
For example, the unique identifier may be the userid which is (probably) stashed away 
in the session, so the above three line segment is really:

  NDC.push((String)session.getAttribute("user.key"));
  log.debug("The message being logged");
  NDC.pop();

This not only adds to the latency (?) it also necessitates the -- otherwise 
unnecessary -- passing of the session object around.  It also muddies logging in the 
business layer that has no notion of sessions.

Further, can't a session's processing get preempted between the push() and the actual 
logging resulting in something like:

John: The message being logged
null: The message being logged

Or am I missing something?

Your thoughts?

Sri

Reply via email to