logback历史日志无法自动删除的问题

例如在logback-spring.xml进行如下配置:

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
	<!-- 路径 /www/wwwroot/zqdsj.pasis.cn-->
	<fileNamePattern>${LOG_HOME}/sc-logs/sc-sys.info.%d.log</fileNamePattern>
	<maxHistory>30</maxHistory>
	<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>

在TimeBasedRollingPolicy类中调用日志清理

//服务启动时执行日志清理
if (cleanHistoryOnStart) {
    addInfo("Cleaning on start up");
    Date now = new Date(timeBasedFileNamingAndTriggeringPolicy.getCurrentTime());
    cleanUpFuture = archiveRemover.cleanAsynchronously(now);
}

调用TimeBasedArchiveRemover类异步清理

public class ArhiveRemoverRunnable implements Runnable {
    Date now;

    ArhiveRemoverRunnable(Date now) {
        this.now = now;
    }
	//异步进行日志清理
    @Override
    public void run() {
        clean(now);
        if (totalSizeCap != UNBOUNDED_TOTAL_SIZE_CAP && totalSizeCap > 0) {
            capTotalSize(now);
        }
    }
}

计算要删除日志的日期,并匹配日志文件进行删除

int callCount = 0;
public void clean(Date now) {

    long nowInMillis = now.getTime();
    // for a live appender periodsElapsed is expected to be 1
    int periodsElapsed = computeElapsedPeriodsSinceLastClean(nowInMillis);
    lastHeartBeat = nowInMillis;
    if (periodsElapsed > 1) {
        addInfo("Multiple periods, i.e. " + periodsElapsed + " periods, seem to have elapsed. This is expected at application start.");
    }
    for (int i = 0; i < periodsElapsed; i++) {
        int offset = getPeriodOffsetForDeletionTarget() - i;
        //获取需要删除的日志日期 如今天是2022-09-15 maxHistory为30 则dateOfPeriodToClean是从2022-08-15到2022-07-15 过早的日志则需要手动删除
        Date dateOfPeriodToClean = rc.getEndOfNextNthPeriod(now, offset);
        cleanPeriod(dateOfPeriodToClean);
    }
}
public void cleanPeriod(Date dateOfPeriodToClean) {
    //根据日期获取要清理的文件
    File[] matchingFileArray = getFilesInPeriod(dateOfPeriodToClean);
	//删除匹配到的文件
    for (File f : matchingFileArray) {
        addInfo("deleting " + f);
        f.delete();
    }

    if (parentClean && matchingFileArray.length > 0) {
        File parentDir = getParentDir(matchingFileArray[0]);
        removeFolderIfEmpty(parentDir);
    }
}

结论:

如果要在项目启动时就删除历史日志文件,需要在logback-spring.xml中添加true

另外,过于古老的日志是无法自动清除的,如今天是2022-09-15 maxHistory为30 则日志删除的范围是从 2022-07-15 到 2022-08-15 ,过早的日志则需要手动删除

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值