From c1820a3d397ce2c9f0bb9d3497875d37f4b028fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9E=D0=BB=D0=B5=D0=B3=20=D0=94=D0=B5=D0=BD=D1=8C=D0=BA?= =?UTF-8?q?=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 8 Feb 2022 20:41:36 +0100 Subject: [PATCH] fix: newest log file is not archived event "rotate" not emitted when app started, it may be have sense because literally rotate code doesn't run, only creating new file happen, but when it happen we can find path to last old log file in auditLog.files and then archive it. (https://github.com/winstonjs/winston-daily-rotate-file/issues/296 issue) --- daily-rotate-file.js | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/daily-rotate-file.js b/daily-rotate-file.js index 203f189..0f43fe5 100644 --- a/daily-rotate-file.js +++ b/daily-rotate-file.js @@ -61,6 +61,24 @@ var DailyRotateFile = function (options) { return !/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(dirname); } + function archive(oldFile) { + var oldFileExist = fs.existsSync(oldFile); + var gzExist = fs.existsSync(oldFile + '.gz'); + if (!oldFileExist || gzExist) { + return; + } + + var gzip = zlib.createGzip(); + var inp = fs.createReadStream(oldFile); + var out = fs.createWriteStream(oldFile + '.gz'); + inp.pipe(gzip).pipe(out).on('finish', function () { + if (fs.existsSync(oldFile)) { + fs.unlinkSync(oldFile); + } + self.emit('archive', oldFile + '.gz'); + }); + } + this.options = Object.assign({}, loggerDefaults, options); if (options.stream) { @@ -124,22 +142,19 @@ var DailyRotateFile = function (options) { }); if (options.zippedArchive) { - this.logStream.on('rotate', function (oldFile) { - var oldFileExist = fs.existsSync(oldFile); - var gzExist = fs.existsSync(oldFile + '.gz'); - if (!oldFileExist || gzExist) { - return; + this.logStream.on('new', function () { + if (self.logStream.auditLog + && self.logStream.auditLog.files + && self.logStream.auditLog.files.length > 1 + && self.logStream.auditLog.files[self.logStream.auditLog.files.length - 2] + ) { + var lastOldFileAfterRestart = self.logStream.auditLog.files[self.logStream.auditLog.files.length - 2].name; + archive(lastOldFileAfterRestart); } + }); - var gzip = zlib.createGzip(); - var inp = fs.createReadStream(oldFile); - var out = fs.createWriteStream(oldFile + '.gz'); - inp.pipe(gzip).pipe(out).on('finish', function () { - if (fs.existsSync(oldFile)) { - fs.unlinkSync(oldFile); - } - self.emit('archive', oldFile + '.gz'); - }); + this.logStream.on('rotate', function (oldFile) { + archive(oldFile); }); }