Q:

Log to a different file according to thread

I have an application with multiple "controllers", and I'd like to have each log to their own file. This is easy enough for their own code, but I'm also using some library code which uses commons logging. Could I somehow get that code to log to the controller-specific file as well?
I was thinking I could somehow do it by thread:
class Controller {

 public void action() {
  setCurrentThreadLogFile(myLogFile);
  try {
   Library.stuff();
  } finally {
   restoreCurrentThreadLogFile();
  }
 }

}

Currently I'm using commons-logging for my own logging as well, with log4j as backend. But I could change that, if needed, or use a mix (is that's possible within the commons logging framework).
One way I could do this would be to write my own commons logging implementation (possibly a wrapper around log4j), but is there an existing solution?

A:

You probably want to be looking at mapped diagnostic contexts (MDCs).  Commons logging does not support these but Log4J does, so you would have to go directly to Log4J to set this up.  You will probably have to roll your own filter to filter using the MDC and apply to the appenders.
If you willing to change logging implementations then you could use SL4J as the logging facade and Logback as the logging implementation.  Have the controller or some sort of  filter/interceptor add a discriminator value for a key you are going to use to discriminate the controllers with to the MDC.  Use a SiftingAppender to separate the log event into separate files.

