Log4j and Logback FileAppender maxFileSize and maxBackupIndex

joao cenoura picture joao cenoura · Oct 8, 2013 · Viewed 7.6k times · Source

I need to control the maximum amount of disk space for my logging framework.
For instance, in log4j, I can easily estimate how much disk space I need if I have an appender like this:

<appender name="appender" class="org.apache.log4j.RollingFileAppender"> 
    <param name="file" value="example.log"/>
    <param name="MaxFileSize" value="100KB"/>
    <param name="MaxBackupIndex" value="10"/>
    <layout class="org.apache.log4j.PatternLayout"> 
        <param name="ConversionPattern" value="%p %t %c - %m%n"/> 
    </layout> 
</appender>

With maxFileSize and maxBackupIndex I know I'll need at most 10x100KB.
I've noticed DailyRollingFileAppender but it doesn't support maxFileSize.

Are there other FileAppenders than RollingFileAppender that can achieve this control? Does logback or log4j2 provide other FileAppenders/alternatives?

Note: I'm looking for ways of configuring the logging framework only, no external processes like crontab with rm command. 3rd party FileAppenders like this, this or this are welcome.

Answer

Sage picture Sage · Oct 8, 2013

Does logback or log4j2 provide other FileAppenders/alternatives

log4j2 introduces RandomAccessFileAppender and RollingRandomAccessFileAppender which are still experimental, may replace FileAppender and RollingFileAppender in a future release. See here.

However current RollingFileAppender requires a TriggeringPolicy:

  • OnStartup Triggering Policy: The OnStartup policy takes no parameters and causes a rollover if the log file is older than the current JVM's start time.

  • SizeBased Triggering Policy: Causes a rollover once the file has reached the specified size. The size can be specified in bytes, KB, MB or GB.

  • TimeBased Triggering Policy: Causes a rollover once the date/time pattern no longer applies to the active file. This policy accepts an "increment" attribute which indicates how frequently the rollover should occur based on the time pattern and a "modulate" boolean attribute.