Bunyan HTTP Middleware Logger

1.0.2 · active · verified Wed Apr 22

bunyan-middleware is a Node.js middleware for logging HTTP requests and responses using the Bunyan logger. Currently at version 1.0.2, it appears to be a stable project, though its release cadence is not explicitly stated. This library offers robust features for integrating structured logging into Express, Connect, or pure HTTP servers. Key differentiators include automatic management of the `X-Request-Id` header (generating a UUID if not present), logging request-response duration, providing a request-scoped logger (`req.log`) for tracing individual requests throughout an application, and custom serializers for `req` and `res` objects. It also provides functionality to obscure sensitive headers in log outputs, enhancing security and compliance. It is a direct dependency of an existing Bunyan logger instance, allowing for consistent logging configuration.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates setting up bunyan-middleware with Express, configuring request ID handling, obscuring headers, adding custom finish data, and utilizing the request-scoped `req.log`.

const bunyan = require('bunyan')
const bunyanMiddleware = require('bunyan-middleware')
const express = require('express')

const app = express()
const logger = bunyan.createLogger({ name: 'My App', level: process.env.LOG_LEVEL || 'info' })

app.use(bunyanMiddleware(
    { headerName: 'X-Request-Id'
    , propertyName: 'reqId'
    , logName: 'req_id'
    , obscureHeaders: ['authorization', 'cookie'] // Example: obscure sensitive headers
    , logger: logger
    , additionalRequestFinishData: function(req, res) {
        // Add custom data to the 'request finish' log message
        return { exampleCustomData: 'value' }
      }
    }
  )
)

app.get('/', function (req, res) {
  // Use `req.log` for request-specific logging, automatically including the request ID.
  req.log.info({ user: 'guest' }, 'Accessed home route')
  res.send('Hello, Bunyan Logger!')
})

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

view raw JSON →