Pino HTTP Logger Middleware

11.0.0 · active · verified Tue Apr 21

pino-http is a high-speed HTTP logger middleware designed for Node.js applications, leveraging the highly performant Pino logging library. It focuses on providing structured JSON logs for HTTP requests and responses with minimal overhead, making it ideal for high-throughput microservices and APIs. The package is currently at version 11.0.0 and follows a release cadence that often aligns with major updates to its underlying `pino` dependency, typically seeing several minor/patch releases throughout the year. Its primary differentiator is its exceptional performance compared to other HTTP loggers, achieved by deferring heavy log processing. It provides extensive customization options for log levels, request ID generation, and structured log data.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `pino-http` with a custom base logger, request ID generation, and dynamic log level based on response status. It includes a basic HTTP server, showcasing how `req.log` is injected for contextual logging and how to use `pino-pretty` for development output.

import http from 'node:http';
import pinoHttp from 'pino-http';
import pino from 'pino';

// Create a base Pino logger (optional, pino-http can create one internally)
const baseLogger = pino({
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  transport: {
    target: 'pino-pretty',
    options: {
      colorize: true
    }
  }
});

const loggerMiddleware = pinoHttp({
  logger: baseLogger,
  genReqId: function (req) {
    // Generate a unique request ID for better traceability
    return req.headers['x-request-id'] || Math.random().toString(36).substring(2, 15);
  },
  customLogLevel: function (req, res, err) {
    if (res.statusCode >= 400 && res.statusCode < 500) return 'warn';
    if (res.statusCode >= 500 || err) return 'error';
    return 'info';
  }
});

const server = http.createServer((req, res) => {
  loggerMiddleware(req, res);

  req.log.info({ url: req.url, method: req.method }, 'Incoming request');

  if (req.url === '/error') {
    req.log.error('Simulating an error');
    res.statusCode = 500;
    res.end('Internal Server Error');
    return;
  }

  res.end('Hello world!');
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  baseLogger.info(`Server listening on port ${PORT}`);
});

// To run: node --loader ts-node/esm your-file.ts (if using ts-node and ESM)
// or: node your-file.js

view raw JSON →