Express Winston Middleware

4.2.0 · active · verified Wed Apr 22

express-winston is an Express.js middleware package that integrates the popular Winston logging library into web applications, enabling structured request and error logging. The current stable version is 4.2.0. The project maintains a somewhat active release cadence, frequently addressing dependency updates, security fixes, and minor feature enhancements within the 4.x series. Its key differentiators include extensive configuration options for filtering request/response metadata (e.g., using whitelists and blacklists, though these terms are slated for removal in v5.x), dynamic log levels, and the ability to leverage any of Winston's powerful transports and formatting capabilities directly within the Express middleware stack for both HTTP request logging and centralized error handling.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up both request and error logging middleware for an Express application. It configures a Winston console transport, logs request and error metadata, and uses dynamic status levels for request logging.

import express from 'express';
import winston from 'winston';
import * as expressWinston from 'express-winston';

const app = express();

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    })
  ]
});

// Request Logger: Logs all incoming HTTP requests
app.use(expressWinston.logger({
  winstonInstance: logger,
  meta: true, // Log request metadata (ip, url, method, body, etc.)
  msg: "HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms",
  colorize: true,
  statusLevels: true // Use different log levels based on HTTP status codes
}));

app.get('/', (req, res) => {
  res.status(200).send('Hello, World! This is a logged request.');
});

app.get('/error-route', (req, res, next) => {
  // Simulate an error
  next(new Error('Oops! Something went wrong on this route.'));
});

// Error Logger: Must be placed after the router but before any other error handling middleware
app.use(expressWinston.errorLogger({
  winstonInstance: logger,
  meta: true, // Log error metadata (stack trace, request info)
  msg: "HTTP Error encountered: {{err.message}}",
  colorize: true
}));

// Custom error handler (after express-winston.errorLogger)
app.use((err, req, res, next) => {
  console.error(`Caught by custom error handler: ${err.message}`);
  res.status(500).send('An unexpected error occurred!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log('Try visiting / and /error-route to see logs.');
});

view raw JSON →