0

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.

Bargain23
  • 1,863
  • 3
  • 29
  • 50

1 Answers1

3

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

Mikko
  • 1,877
  • 1
  • 25
  • 37
  • How would `pm2-logrotate ` rotate the logs if they're managed by winston? How does pm2 know the location of the logs? – gaganshera Oct 18 '22 at 08:42