Since 2.5, Log4j supports a custom Delete action that is executed on every rollover.
You can control which files are deleted by any combination of:
- Name (matching a glob or a regex)
- Age (“delete if 14 days old or older”)
- Count (“keep only the most recent 3”)
- Size (“keep only the most recent files up to 500MB”)
Users who need even more fine-grained control over which files to delete can specify a script condition using any supported JSR-223 scripting language.
Please check out the documentation, it has three full examples that may be useful.
For your question, this snippet should work:
<RollingFile name="rollingFile"
fileName="/path/app.log"
filePattern="/path/app.%d{yyyy-MM-dd}.log"
ignoreExceptions="false">
. . .
<DefaultRolloverStrategy>
<!--
* only files in the log folder, no sub folders
* only rolled over log files (name match)
* only files that are 4 days old or older
-->
<Delete basePath="${sys:storm.home}/logs/" maxDepth="1">
<IfFileName glob="*.service.????????" />
<IfLastModified age="4d" />
</Delete>
</DefaultRolloverStrategy>
. . .
<RollingFile>
Finally, be careful! There is no way to recover files deleted this way. 🙂