开发者

Log to a different file according to thread

开发者 https://www.devze.com 2023-02-14 06:00 出处:网络
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

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开发者_Go百科 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?


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.


A logger per thread? Put the logger in a ThreadLocal. If you are using java.util.logging, a Handler could make this transparent to the caller.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号