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.

4 comments:

Anonymous said...

I read your article. I had the problem that you comment here, but I found that the problem was caused by having two applications in my tomcat using the same file. In fact, it was the same application that was deployed two times with different names. To solve it, just stop one of the applications.
Maybe it helps.

Unknown said...

Yes you are very right about it Sergio.
When you were using two applications for same log file, there were two processes access same resource and hence the contention occured.

My guess is, Windows doesn't allow sharing of resource while on Unix, you might not get the any error.


Viraj

Freeman said...

this might be useful
http://minaret.biz/tips/datedFileAppender.html
its a replacement for DailyRollingFileAppender which logs directly to the log'.'yyyy-mm-dd file
everyday, so it doesn't have to move files.

Anonymous said...

datedFileAppender worked for me :).
You just have to re-configure the properties file to match the new configuration settings (Directory, Prefix, et cetera).