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
相关产品推荐
相关产品推荐

