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

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配置文件。由于是指定目录,指定文件名格式,指定日期范围,所以是可以清除非工程目录下的文件,所以一定不要配置错了。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

markvivv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值