Using MDC in log4j to dynamically name the log file

Shamis Shukoor picture Shamis Shukoor · Nov 3, 2011 · Viewed 13.6k times · Source

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.

Answer

Dan picture Dan · Nov 3, 2011

This can be accomplished in Logback, the successor to Log4J.

Logback is intended as a successor to the popular log4j project, picking up where log4j leaves off.

See the documentation for Sifting Appender

The SiftingAppender is unique in its capacity to reference and configure nested appenders. In the above example, within the SiftingAppender there will be nested FileAppender instances, each instance identified by the value associated with the "userid" MDC key. Whenever the "userid" MDC key is assigned a new value, a new FileAppender instance will be built from scratch. The SiftingAppender keeps track of the appenders it creates. Appenders unused for 30 minutes will be automatically closed and discarded.

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.