Tuesday, December 13, 2005

log4j DailyRollingFileAppender

Wanted to log messages in my J2EE web application in new log file everyday.
Log4j is the best option for that. (BEST.. because I know how to use it :))
Using "DailyRollingFileAppender" is the solution.

It is not as simple as it seems to be.
I conveniently made one log4j.xml, put it in /WEB-INF/classes and started working on other things.
Every morning I saw some weird error message saying something like
log4j:ERROR Failed to rename [logfilename] to [logfilename.2005.12.11]
I also observed that, NO new log file is created.

Searching on the net suggested that error is because of “multiple processes accessing same file”.
Because of multiple processes, accessing my log file, renaming was not possible.

We need to deinitialize/initialize logging mechanism every time we restart the server to terminate processes accessing log files.
To achieve this, I wrote one small listener implementing javax.servlet.ServletContextListener interface.
Everytime when context was destroyed, I shutdown log4j’s logging mechanism using org.apache.log4j.LogManager.shutdown() method.
Shutting down the mechanism made sure that all the processes that are using log files are terminated and this way resolved the issue.

Try it and do let me know whether this solved your problem or not.
Please let me know if there is better solution for this.

Thanks.