Production Logging & Monitoring - Winston, Morgan & Structured JSON Logs

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.

Installing Winston & Morgan

npm install winston morgan winston-daily-rotate-file

Configuring Winston: logger.js

const 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;

Integrating Morgan with Winston in Express

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()) }
}));

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is console.log() unacceptable in production Node.js applications?

console.log() is synchronous when writing to certain terminals, which can block the event loop under heavy load. It also lacks log severity levels (info, warn, error), timestamps, structured JSON formatting for log aggregators (Datadog, ELK), and automated disk file rotation.

Q2. What is Winston and how do log levels work?

Winston is the most popular logging library for Node.js. It adheres to RFC5424 severity levels: error (0), warn (1), info (2), http (3), verbose (4), debug (5), and silly (6). You can configure it to log debug messages in development and only info/error in production.

Q3. What does Morgan do in an Express application?

Morgan is an HTTP request logger middleware for Node.js. It automatically intercepts every incoming request and logs the HTTP method, URL, status code, response time in ms, and user-agent.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Error Handling Best Practices

Log uncaught exceptions to persistent log files.

Performance Profiling

Monitor memory and event loop lag.

Docker & PM2 Deployment

Manage stdout/stderr streams in containers.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!