log4j 重写DailyRollingFileAppender 自定义日志文件名

log4j 重写DailyRollingFileAppender 自定义日志文件名

背景

我们要对非当日的日志进行压缩,运维要求日志文件后缀必须是xxx.log 这种格式的,但是非当天日志文件后缀,比如今天是20230414,那么20230413的日志后缀 DailyRollingFileAppender默认的是 xxx.log.2023-04-13,这样就不满足压缩规则,所以我们必须要改成xxx_2023-04-13.log这种格式的。
重写的话,首先需要看看人家本身是怎么实现的

DailyRollingFileAppender 源码

主要看一下两个方法就可以。
activateOptions() 会初始化一个scheduledFilename 文件名称,会根据设置的文件名称+datePattern(默认值为datePattern = “'.'yyyy-MM-dd”)

public void activateOptions() {
   
        super.activateOptions();
        if (this.datePattern != null && this.fileName != null) {
   
            this.now.setTime(System.currentTimeMillis());
            this.sdf = new SimpleDateFormat(this.datePattern);
            int type = this.computeCheckPeriod();
            this.printPeriodicity(type);
            this.rc.setType(type);
            File file = new File(this.fileName);
            this.scheduledFilename = this.fileName + this.sdf.format(new Date(file.lastModified()));
        } else {
   
            LogLog.error("Either File or DatePattern options are not set for appender [" + this.name + "].");
        }

    }

rollOver() 为定期的执行,判断当天文件名和scheduledFilename 是否相等,看是否需要重写文件后缀名

void rollOver() throws IOException {
   
        if (this.datePattern == null) {
   
            this.errorHandler.error("Missing DatePattern option in rollOver().");
        } else {
   
            String datedFilename = this.fileName + this.sdf.format(this.now);
            if (!this.scheduledFilename.equals(datedFilename)) {
   
                this.closeFile();
                File target = new File(this.scheduledFilename);
                if (target.exists()) {
   
                    target.delete();
                }

                File file = new File(this.fileName);
                boolean result = file.renameTo(target);
                if (result) {
   
                    LogLog.debug(this.fileName + " -> " + this.scheduledFilename);
                } else {
   
                    LogLog.error("Failed to rename [" + this.fileName + "] to [" + this.scheduledFilename + "].");
                }

                try {
   
                    this.setFile(this.fileName, true, this.bufferedIO, this.bufferSize);
                } catch (IOException var6) {
   
                    this.errorHandler.error("setFile(" + this.fileName + ", true) call failed.");
                }

                this.scheduledFilename = datedFilename;
            }
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值