module Logging::NestedDiagnosticContext

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.

The NDC is a stack of contextual messages that are pushed and popped by the client as different contexts are encountered in the application. When a new context is entered, the client will ‘push` a new message onto the NDC stack. This message appears in all log messages. When this context is exited, the client will call `pop` to remove the message.

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.

When configured to do so, PatternLayout instance will automatically retrieve the nested diagnostic context for the current thread with out any user intervention. This context information can be used to track user sessions in a Rails application, for example.

Note that NDCs are managed on a per thread basis. NDC operations such as ‘push`, `pop`, and `clear` affect the NDC of the current thread only. NDCs of other threads remain unaffected.

By default, when a new thread is created it will inherit the context of its parent thread. However, the ‘inherit` method may be used to inherit context for any other thread in the application.