winstonjs / winston-daily-rotate-file

A transport for winston which logs to a rotating file each day.
MIT License
889 stars 151 forks source link

Awaiting logs to be written in winston #382

Open akotulu opened 11 months ago

akotulu commented 11 months ago

From winston docs

const transport = new winston.transports.Console();
const logger = winston.createLogger({
  transports: [transport]
});

logger.on('finish', function (info) {
  // All `info` log messages has now been logged
});

logger.info('CHILL WINSTON!', { seriously: true });
logger.end();

This is fine and works for console, but with daily rotate file transport last entry wont be written. Here is a demo node project, it waits for user interrupt for 10 seconds.

import winston from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
import {setTimeout} from "timers/promises";

const log = winston.loggers.add(import.meta.url, {
  transports: [
    new DailyRotateFile({
      filename: process.cwd() + `/logs/wdrf_%DATE%.log`,
      datePattern: 'YYYY-MM-DD',
      level: winston.default_log_level || 'info',
      maxFiles: 7,
    }),
    new winston.transports.Console({
      level: winston.default_log_level || 'debug',
    }),
  ],
  exitOnError: false
});

process.on('SIGINT', exit);
process.on('SIGHUP', exit);
process.on('SIGQUIT', exit);
process.on('SIGTERM', exit);

/*
 * Exit signal handler.
 */
function exit(signal) {
  log.info(`Received signal ${signal}`);
  log.info('Closing resources');

  let promises = [];

  for (let [, logger] of winston.loggers.loggers) {
    promises.push(new Promise((resolve) => {
      logger.on('finish', resolve);
      logger.end();
    }));
  }

  Promise.allSettled(promises).then(_ => {
    process.exit();
  });
}

new Promise(resolve => setTimeout( 10000, resolve))
  .finally();

Console output:

^C{"level":"info","message":"Received signal SIGINT"}
{"level":"info","message":"Closing resources"}

File output:

{"level":"info","message":"Received signal SIGINT"}

This isn't a mayor issue, but still relevant as last line is missing from file.