Using Log4j
As @JavaJigs said, Log4j's extras can be used.
First of all, if you're using Maven, add it as dependency keeping in mind to use the same log4j version, just to avoid any kind of conflict.
<!-- you should already have something like this -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- add this one, please note the version is the same than log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.2.17</version>
</dependency>
Then, set up an appender to use both kinds of rollings. This is a quick and dirty example that rolls every minute and / or when the size of the log files exceeds 1000 bytes.
<appender name="rollout5" class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="ActiveFileName" value="log4j-current.log" />
<param name="FileNamePattern" value="log4j-%d{HH-mm}.%i.log.gz" />
</rollingPolicy>
<triggeringPolicy class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
<param name="MaxFileSize" value="1000" />
</triggeringPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n" />
</layout>
</appender>
Add the appender to the logger as you usually do.
If you run the application you should obtain something like that...
log4j-current.log
log4j-18-13.1480266729211.log.gz
log4j-18-12.1480266729095.log.gz
log4j-18-12.1480266729123.log.gz
Obviously the numbers of files and their names depend on how your application logs.
As you can see, the %i
placeholder gets replaced with a sort of random yet ever increasing number. I was not able to find a way to have it replaced with number starting from 0 though. Nevertheless, such files listed in alphabetic order should match their historical order.
Other ideas
I know you mentioned explicitly log4j. But, if you can, why not to evaluate moving to log4j2? In this log4j2 piece of doc there are a couple of examples that seem to suit your needs.