I'm using log4j 2 and RollingFile appender:
<RollingFile name="mylog"
fileName="mylog.log"
filePattern="mylog.log.%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%d] [%-5p] [%-8t] %F:%L %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
</Policies>
</RollingFile>
The log files do get renamed daily. But the Javadoc of FileRenameAction
class indicates there is an option renameEmptyFiles
which is false by default so if a day's log is empty it deletes it instead of rename it appending the date to the file name. How to configure it to true since I'd like to have the log file even if it's empty?
I made a little plugin that offers the desired functionality. I simply extended the
DefaultRolloverStrategy
and replaced (as all of its fields arefinal
) theRolloverDescription
object that is returned fromrollover()
. I copied the static@PluginFactory
code fromDefaultRolloverStrategy
as it's required for the Log4j 2 plugin system.Here's the code:
To use this class, simply reference it in the Log4j 2 XML configuration, e.g. like this:
The implementation was inspired by this related answer.
On a sidenote, it might be necessary to use the new
CronTriggeringPolicy
to have empty log files being created at all, as it uses a separate thread. Judging from some other answers on SO, at least some of the other policies cannot react to the trigger as long as the Appender doesn't write out anything.