Is it possible some how to use MDC to name the log file at run time.
I have a single web application which is being called by different names at the same time using tomcat docbase. So i need to have separate log files for each of them.
Is it possible some how to use MDC to name the log file at run time.
I have a single web application which is being called by different names at the same time using tomcat docbase. So i need to have separate log files for each of them.
This can be accomplished in Logback, the successor to Log4J.
See the documentation for Sifting Appender
In the example, they generate a separate log file for each user based on an MDC value. Other MDC values could be used depending on your needs.
This is also possible with log4j. You can do this by implementing your own appender. I guess the easiest way is to subclass AppenderSkeleton.
All logging events end up in the
append(LoggingEvent event)
method you have to implement.In that method you can access the MDC by
event.getMDC("nameOfTheKeyToLookFor");
Then you could use this information to open the file to write to. It may be helpful to have a look at the implementation of the standard appenders like RollingFileAppender to figure out the rest.
I used this approach myself in an application to separate the logs of different threads into different log files and it worked very well.
I struggled for a while to find SiftingAppender-like functionality in log4j (we couldn't switch to logback because of some dependencies), and ended up with a programmatic solution that works pretty well, using an MDC and appending loggers at runtime:
The filter appended above just checks for a specific process id:
Hope this helps a bit.