node.jsloggingpm2winstonlog-rotation

How do I combine Winston and pm2 for logging that rotates at a specific schedule


My node application is currently using Winston for console logging, but there are various issues that are difficult to debug on the development environment. I need to create a logger that logs warnings and errors only and saves the logs to a text file. It should rotate interval and restarts every midnight of Sunday. This is my current logger using Winston:

'use strict';

const winston = require('winston');
const m = require('moment-timezone');
let logger = null;

/**
 * Initializes the logger
 * @param {object} configLogging
 */
module.exports.initialize = function initialize(configLogging) {
  const dateFormat = 'dddd, MMMM Do YYYY, h:mm:ss a';

  logger = new winston.Logger({
    transports: [
      new (winston.transports.Console)({
        name: 'info-console',
        level: configLogging.level,
        colorize: true,
        timestamp: function() { return m.utc().format(dateFormat); }
      })
    ]
  });

  logger.info('Starting logging service');
};

/**
 * Gets the logger instance
 * @returns {LoggerInstance} winLogger
 */
module.exports.get = function get() {
  return logger;
};

I heard that pm2-logrotate should be able to do what I want, but I'm not sure how I can integrate it to my app.


Solution

  • You need to configure pm2 to handle the log rotation. In your code, first set winston to log to a file (winston.transports.File) with the level warn.

    Then install pm2 logrotate from console:

    pm2 install pm2-logrotate

    configure it:

    pm2-logrotate:rotateInterval '0 0 * * 0' //every sunday at midnight

    see more configuration options from the documentation

    Start your app: pm2 start, and when all looks good save the config: pm2 save