Contextual Logging in Log4j

Just caught an interesting post come through JavaBlogs regarding Atlassian‘s approach to providing additional context when logging errors in Confluence.

It brought something to my attention that was previously unknown, that is the Log4j mapped diagnostic contexts (not to be confused with the nested diagnostic contexts or NDCs). See the log4j wiki entry on NDCvsMDC.

Evidently I live in a cave (or perhaps have been using commons-logging for too long) but basically a MDC is a thread-local’d structure exposing a map-like interface that, depending on your logging pattern, can be included in your logged messages. Particularly useful stuff if you’re developing a multi-threaded system (be it swing, j2ee or some other inherently multi-threaded framework) and want to provide useful debugging information.

UltraLightClient has an entry in their code community providing a logging example using MDC and Log4j.

Nice and simple.