Rolling logs by both size and time

Michael picture Michael · Dec 18, 2012 · Viewed 14.1k times · Source

I use RollingFileAppender of log4j 1.2.16, which rolls log files, when they reach a certain size. Now I would like to roll log files daily and when they reach a certain size. Thus there will be one or more log files per day.

For example,

myapp.log
myapp-17.12.2013.log
myapp-16.12.2012.log
myapp-16.12.2012.1.log
myapp-16.12.2012.2.log

Is there an off-the-shelf appender, which does it already?

Answer

David Peleg picture David Peleg · Jan 7, 2013

There are indeed two options:

  1. use LogBack with its size and time triggering policy: http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedFNATP
  2. there is TimeAndSizeRollingAppender for Log4J from here: http://www.simonsite.org.uk/

Keep in mind that both options use file renames. Consider this carefully if there's another script automatically moving these files. File rename is risky when two processes deal with the same file.

My suggestion is to directly write to immutable log file name in the pattern: myapp-{dd.MM.yyyy}.{X}.log. That way "rolling" is simply closing one file and opening a new one. No renames. No background threads.