When an API crashes or responds slowly in production, you cannot open VS Code and debug live user sessions. You need structured, persistent Log Files. In this tutorial, you will configure Winston for multi-transport JSON logging and Morgan for HTTP traffic metrics.
npm install winston morgan winston-daily-rotate-file
logger.jsconst winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const { combine, timestamp, printf, json, colorize } = winston.format;
// Custom human-readable format for development terminal
const consoleFormat = printf(({ level, message, timestamp, stack }) => {
return `[${timestamp}] ${level}: ${stack || message}`;
});
const logger = winston.createLogger({
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
format: combine(timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), json()),
transports: [
// 1. Daily Rotating File for Errors
new DailyRotateFile({
filename: 'logs/error-%DATE%.log',
datePattern: 'YYYY-MM-DD',
level: 'error',
maxSize: '20m',
maxFiles: '14d' // Retain for 14 days
}),
// 2. Daily Rotating File for All Logs (Combined)
new DailyRotateFile({
filename: 'logs/combined-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d'
})
]
});
// If not in production, log to console with vibrant colors!
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: combine(colorize(), timestamp({ format: 'HH:mm:ss' }), consoleFormat)
}));
}
module.exports = logger;
const express = require('express');
const morgan = require('morgan');
const logger = require('./logger');
const app = express();
// Stream Morgan HTTP request logs into Winston
app.use(morgan('combined', {
stream: { write: (message) => logger.info(message.trim()) }
}));
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Log uncaught exceptions to persistent log files.
Monitor memory and event loop lag.
Manage stdout/stderr streams in containers.