logger.js•1.65 kB
const winston = require('winston');
// Define log levels
const levels = {
error: 0,
warn: 1,
info: 2,
http: 3,
debug: 4,
};
// Define colors for each level
const colors = {
error: 'red',
warn: 'yellow',
info: 'green',
http: 'magenta',
debug: 'white',
};
// Tell winston about the colors
winston.addColors(colors);
// Format function
const format = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
winston.format.colorize({ all: true }),
winston.format.printf(
(info) => `${info.timestamp} ${info.level}: ${info.message}`
)
);
// Define which transports the logger must use
const transports = [
// Console transport
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
),
}),
// File transport for errors
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
}),
// File transport for all logs
new winston.transports.File({
filename: 'logs/combined.log',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
}),
];
// Create the logger
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
levels,
format,
transports,
});
// Create a stream object with a 'write' function that will be used by Morgan
logger.stream = {
write: (message) => {
// Remove the trailing newline
logger.http(message.trim());
},
};
module.exports = logger;