log4j configurations with daily rolling, gzip and max backup files

Udy picture Udy · Oct 27, 2013 · Viewed 9.1k times · Source

Is there an appender that I can use that will get me daily rolling, compression and max files?

I can get daily rolling file with compression using apache-log4j-extras with this configuration:

<appender name="debugFileRolling" class="org.apache.log4j.rolling.RollingFileAppender">
    <!-- The active file to log to -->
    <param name="file" value="debug.log" />
    <param name="append" value="true" />
    <param name="encoding" value="UTF-8" />
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" value="/%d{yyyy-MM-dd}-debug.log.gz" />
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d [%t] %c: %m%n" />
    </layout>
</appender>

But I can't specify MaxBackupIndex as in org.apache.log4j.RollingFileAppender (note the slight namespace difference between the two).

I would like both without having to implement my own FileAppender, TriggeringPolicy, or RollingPolicy.

Answer

Uli picture Uli · Dec 15, 2014

log4j 1.2 does not have an appender that supports all features required by you. You have to use your own implementation.

log4j2 seems to support your requirements. Please have a look at the log4j2 documentation:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <RollingFile name="RollingFile" fileName="logs/app.log"
       filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="250 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="20"/>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>
</Configuration>