You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Winston普通File传输日志文件名递增2,如何改为每次递增1?

Winston普通File传输日志轮转序号递增问题解决

问题描述

使用Winston的普通File传输(非winston-daily-rotate-file)配置日志轮转后,生成的日志文件名序号每次递增2(例如myApp.log、myApp1.log、myApp3.log、myApp5.log),希望将序号改为每次递增1。配置代码如下:

this.logger = createLogger({
      transports: [
        new (transports.File)({
          filename: this.getFileName(),
          maxsize: rotationFileSizeMb * 1024 * 1024,
          maxFiles: rotationFileCount,
          format: format.printf(info => this.logFormatter(info)),
          level: logLevel,
        })
      ]
    });

...
...

  private getFileName(): string {
    return `${this.tgpFolder}/var/log/${this.appCode}.log`;
  }

原因与解决方案

问题原因

序号跳增是因为Winston默认轮转逻辑会尝试将当前日志文件重命名为带序号的文件,如果目标序号的文件已存在(比如手动删除过中间序号的日志),就会自动递增序号直到找到可用的文件名,最终导致序号不连续。

解决办法

方法1:清理现有非连续日志文件

  • 停止应用,删除所有带序号的日志文件(如myApp1.log、myApp3.log等),仅保留当前的myApp.log
  • 重启应用后,后续轮转生成的日志会从myApp1.log开始,序号依次递增1

方法2:自定义轮转文件名生成逻辑

若不想删除现有文件,可通过自定义onRotate钩子或扩展File传输类来实现连续序号:

const fs = require('fs');
const path = require('path');

// 获取下一个连续的日志序号
function getNextLogSeq(baseFilePath) {
  const logDir = path.dirname(baseFilePath);
  const baseName = path.basename(baseFilePath, '.log');
  const existingLogs = fs.readdirSync(logDir).filter(file => {
    const reg = new RegExp(`^${baseName}(\\d+)\\.log$`);
    return reg.test(file);
  });

  if (existingLogs.length === 0) return 1;
  const maxSeq = Math.max(...existingLogs.map(file => {
    const match = file.match(/(\d+)\.log$/);
    return match ? parseInt(match[1], 10) : 0;
  }));
  return maxSeq + 1;
}

// 修改Logger配置
this.logger = createLogger({
  transports: [
    new transports.File({
      filename: this.getFileName(),
      maxsize: rotationFileSizeMb * 1024 * 1024,
      maxFiles: rotationFileCount,
      format: format.printf(info => this.logFormatter(info)),
      level: logLevel,
      // 自定义轮转时的文件名
      onRotate: (oldFile, newFile) => {
        const basePath = this.getFileName();
        const nextSeq = getNextLogSeq(basePath);
        const targetFile = `${path.dirname(basePath)}/${path.basename(basePath, '.log')}${nextSeq}.log`;
        fs.renameSync(oldFile, targetFile);
      }
    })
  ]
});

注:确保使用的Winston版本支持onRotate回调,若版本不兼容,可直接扩展Winston的File传输类来覆写默认轮转逻辑。

内容的提问来源于stack exchange,提问作者Ash McConnell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:05:43