tags:

views:

1557

answers:

4

I use log4j with the "RollingFileAppender" to create a log rotation based on a certain size per file. How can I configure it to log to each file for a certain amount of time before rotating? For example, so that each log file contains one hour of logs, rotating at the top of each hour? BTW, I configure log4j programatically in Java using a Properties object (as opposed to a log4j.properties file)

Thanks for any help!

+2  A: 

Use a DailyRollingFileAppender.

In particular, setting its 'datePattern' property to '.'yyyy-MM-dd-HH would cause file to rotate every hour.

ChssPly76
+6  A: 

You probably want to use a DailyRollingFileAppender. To roll them hourly, for example, you'd use a DatePattern of '.'yyyy-MM-dd-HH. For a log4j.properties file:

log4j.appender.myAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myAppender.DatePattern='.'yyyy-MM-dd-HH
...

Or for your programmatic configuration:

DailyRollingFileAppender appender = new DailyRollingFileAppender();
appender.setDatePattern("'.'yyyy-MM-dd-HH");

Logger root = Logger.getRootLogger();
root.addAppender(appender);

Unfortunately, using a DailyRollingFileAppender means that you can't limit the file size - this could be problematic if you have tons of logs in the given rolled period.

Rob Hruska
+2  A: 

The other thing to be careful of with any rolling file appender is to make sure only one vm access a particular log file at a time. This is because log4j caches the log file size for performance reasons, and your 'rolling' will get wonky if multiple vm's access the sames files.

Nathan Feger
Sorry, what do you mean by "vm"?
ZenBlender
I mean the java virtual machine. Each instance of the 'java' executable.
Nathan Feger
A: 

You need to use the DailyRollingFileAppender. Despite its misleading name it can be configured in a to run at configurable time periods up to minutes.

Tendayi Mawushe