Sunday, June 9, 2019

Node.JS: winston custom logger with file rotation

How much easy to have logs in a separate file based on log level which is rotational?

Below is the simple logger.js file, which I have written the code to rotate the files once it reached the size of 10mb.

var winston = require('winston');
var DailyRotateFile = require('winston-daily-rotate-file');
var fs = require('fs');
var path = require('path');

const env = process.env.NODE_ENV || 'development';
const logDir = 'log';

if(!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}

const errorLogsFileTransport = new DailyRotateFile({
    filename: `${logDir}/error-logs-%DATE%.log`,
    datePattern: 'YYYY-MM-DD',
    maxSize: '10k',
    level: 'error',
    zippedArchive: true
})

const debugLogsFileTransport = new DailyRotateFile({
    filename: `${logDir}/debug-logs-%DATE%.log`,
    datePattern: 'YYYY-MM-DD',
    maxSize: '10k',
    level: 'debug',
    zippedArchive: true
})

const infoLogsFileTransport = new DailyRotateFile({
    filename: `${logDir}/info-logs-%DATE%.log`,
    datePattern: 'YYYY-MM-DD',
    maxSize: '10k',
    level: 'info',
    zippedArchive: true
})

const logger = winston.createLogger({
    level: env === 'development' ? 'debug' : 'info',
    format: winston.format.combine(
        winston.format.label({ label: path.basename(process.mainModule.filename)}),
        winston.format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        winston.format.json()
    ),
    transports: [
        new winston.transports.Console({
            level: 'info',
            format: winston.format.combine(
                winston.format.printf(
                    info => `${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
                )
            )
        }),
        errorLogsFileTransport,
        debugLogsFileTransport,
        infoLogsFileTransport
    ]
});

module.exports = logger;