Inherit appenders from calling instance in log4j or logback
In my program I have 2 separate streams of logging events (calling them streams for simplicity, in reality its 2 appenders). Stream1 contains client logging and Stream2 contains control logging. Now this might seem easy, except that certain classes can be both in th开发者_C百科e client logging and server logging, depending on the situation. Complicating this further is the fact that a command that a client wants takes place in 2 separate threads (one being fetched randomly from a thread pool), so any kind of tracking with MDC or NDC isn't possible.
What would really simplify this is if the logger could inherit the appenders from the calling instance. That way I can setup 2 appenders for 2 loggers and be done. However I have no idea how to do it cleanly or easily. Can anyone offer any advice on how to do so?
Note: If something needs to be passed around, I do have a event bean that gets passed to everything in the chain that can be used if necessary.
You've already mentioned that the client processing takes place in multiple threads, so a simple ThreadLocal
approach might not work... but would a ThreadGroupLocal
work?
See [Are there thread group-local variables in Java?
The tact I am suggesting is to only have one appender registered with the logging framework. That appender would be something you write. The implementation would delegate to the ThreadLocal/ThreadGroupLocal appender. The that appender would be client- or control-specific.
Also note that your appender should not be configured beneath asynchronous or batching abstractions.
精彩评论