The normal behavior of the Log4j RollingFileAppender is to roll when the first log message occurs on a different day, but some feel warm and fuzzy with empty logfiles for开发者_开发百科 each date, even if nothing occurred. Is there a way to force it to roll after midnight without writing dummy messages to the log?
I've looked at this code very closely - the simple answer is 'no'. The rollover is triggered as part of the doAppend() flow on the Appender - the only way to trigger it is to log something.
You could fake this with cron: just have a cron script touch the file for tomorrow at like 11:58. That will get you the empty logfile behavior you're looking for.
Here's the code that implements the rollover function:
void rollOver() throws IOException {
/* Compute filename, but only if datePattern is specified */
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName+sdf.format(now);
// It is too early to roll over because we are still within the
// bounds of the current interval. Rollover will occur once the
// next interval is reached.
if (scheduledFilename.equals(datedFilename)) {
return;
}
// close current file, and rename it to datedFilename
this.closeFile();
File target = new File(scheduledFilename);
if (target.exists()) {
target.delete();
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(fileName +" -> "+ scheduledFilename);
} else {
LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"].");
}
try {
// This will also close the file. This is OK since multiple
// close operations are safe.
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
}
catch(IOException e) {
errorHandler.error("setFile("+fileName+", false) call failed.");
}
scheduledFilename = datedFilename;
}
精彩评论