Log4j2配置自动清除指定日期前的日志

  • Post author:
  • Post category:其他




Log Archive Retention Policy: Delete on Rollover




Log4j-2.5 introduces a Delete action that gives users more control over what files are deleted at rollover time than what was possible with the DefaultRolloverStrategy max attribute. The Delete action lets users configure one or more conditions that select the files to delete relative to a base directory.



Note that it is possible to delete any file, not just rolled over log files, so use this action with care! With the testMode parameter you can test your configuration without accidentally deleting the wrong files.


当按照日期归档日志的时候,由于日志会一直存在,导致磁盘空间占用,如果服务器磁盘空间不足,且日志又没有长期保留的必要,可以直接在log4j2.xml中增加配置实现自动清理历史日志,Log4j2官方从2.5版本开始提供按照策略删除日期的功能。log4j2.xml样例配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Don't forget to set system property
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
     to make all loggers asynchronous. -->
<Configuration status="INFO" monitorInterval="120">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %p %c{1.}:%L[%t] %m%n" />
        </Console>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${log4j:configParentLocation}/../logs/info.log" filePattern="${log4j:configParentLocation}/../logs/info-%d{MM-dd-yyyy}.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
            <DefaultRolloverStrategy>
                <Delete basePath="${log4j:configParentLocation}/../logs/" maxDepth="1">
                    <IfFileName glob="info-*.log.gz" />
                    <IfLastModified age="30d" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <logger name="org.springframework" level="INFO" />
        <Root level="DEBUG">
            <AppenderRef ref="RollingRandomAccessFile" />
        </Root>
    </Loggers>
</Configuration>


关注其中的DefaultRolloverStrategy配置内容,按照此配置会自动清除Delete元素中指定basePath下超出30天的info-*.log.gz配置文件。由于是指定目录,指定文件名格式,指定日期范围,所以是可以清除非工程目录下的文件,所以一定不要配置错了。



版权声明:本文为xieshaohu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。