Install libs
npm i moment
npm i winston
npm i winston-daily-rotate-file
Setup
import moment from "moment";
const winston = require('winston');
require('winston-daily-rotate-file');
const environment = process.env.NODE_ENV || 'dev';
// @nhancv 2019-09-10: Format log with specific timezone
const logFormat = winston.format.combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.align(),
winston.format.printf(
info => moment(info.timestamp).utc().utcOffset("+0700").format() + '-' + environment + '-message:' + info.message
),
);
// @nhancv 2019-09-10: Config for file transport
const fileTransport = new winston.transports.DailyRotateFile({
filename: './logs/%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
handleExceptions: true,
zippedArchive: false,
maxSize: '20m',
maxFiles: '15d'
});
// @nhancv 2019-09-10: Config for console transport
const consoleTransport = new winston.transports.Console({
handleExceptions: true,
});
// @nhancv 2019-09-10: Create new logger id
winston.loggers.add('Logger', {
format: logFormat,
transports: [
fileTransport,
consoleTransport,
]
});
// @nhancv 2019-09-10: Get logger from logger ID
const logger = winston.loggers.get('Logger');
// @nhancv 2019-09-06: Catch all unhandled Promise rejections
process.on('unhandledRejection', function (err) {
logger.error(err);
});