Script Valley
Express.js: APIs and Middleware
Middleware Deep DiveLesson 2.2

How to write a custom logging middleware in Express

custom middleware function, req.method, req.url, Date.now timing, res.on finish event, response status logging, middleware placement

Custom Request Logger Middleware

A logger middleware records each request as it comes in and logs the response status after the response finishes. The res.on('finish') event fires after the response is sent — that's where you capture the status code.

Basic request logger

function logger(req, res, next) {
  const start = Date.now();
  const { method, url } = req;

  res.on('finish', () => {
    const duration = Date.now() - start;
    const status = res.statusCode;
    console.log(`[${new Date().toISOString()}] ${method} ${url} ${status} - ${duration}ms`);
  });

  next();
}

module.exports = logger;

Using the logger

const express = require('express');
const logger = require('./middleware/logger');
const app = express();

app.use(logger); // must come before routes

app.get('/hello', (req, res) => {
  res.json({ message: 'hi' });
});

app.listen(3000);

Output: [2024-01-15T10:30:00.000Z] GET /hello 200 - 3ms

Register the logger before any routes so it wraps all requests. Libraries like morgan do this pattern with more options — but writing one yourself teaches you how all logging middleware works under the hood.

Up next

How to write request validation middleware in Express

Sign in to track progress