You can use Log4J's NDC class to add contextual information to the logging output of a particular thread, which you can output using the %x option of an appender's PatternLayout configuration. In a multi-threaded environment the loging output of different theads will inevitably end up as an unordered mess, and while outputting the thread name with the %t option helps, sometimes more information is needed. This is especially true when using pooled threads. The NDC basically maintains a thread local stack on which you can push bits of information about a particualar execution context as soon as you enter it, and from which you should pop that information as soon as you leave the context. An execution context is whatever you need it to be, it could simply be a method, it could span multiple methods, or it could be a part of a method.
The MDC class serves the exact same purpose, but it uses a thread local map, as opposed to a stack to track the contextual information.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
That's faily straightforward, suppose the doSomething() method is invoked frequently from multiple threads:
Everytime you write to a Logger in between those NDC.push() and NDC.pop() calls, the identifier for the Foo object will be part of the logging output, assuming you're using the appropriate PatternLayout.
The reason it's surrounded by a try..finally is to make sure that the context information in the log file will always be correct, even if the code inbetween NDC.push() and NDC.pop() throws an exception.
Also note that if the doSomething() method were the first call to push() within scope of a thread's run() method, the finally block should not call NDC.pop(), but NDC.remove() instead.