Express Bunyan Logger Middleware

raw JSON →
1.3.3 verified Thu Apr 23 auth: no javascript abandoned

express-bunyan-logger is an Express middleware that integrates the Bunyan structured logger into web applications. It automatically logs incoming requests and outgoing responses, enriching log entries with detailed metadata such as HTTP method, URL, response status, and response time. It supports flexible configuration for log formats, custom levels based on response status or time, and dynamic inclusion/exclusion of fields. The current stable version is 1.3.3, last published 8 years ago. However, the project's original maintainer has openly stated a lack of time for ongoing maintenance, indicating an effectively abandoned status. While functional, new feature development and proactive security updates are unlikely. Its primary differentiator is deep integration with Bunyan's serialization capabilities, providing rich, machine-readable logs suitable for analysis and integration with log management tools.

error Error: Cannot find module 'bunyan'
cause The `bunyan` package, which is a core dependency, has not been installed.
fix
Install Bunyan: npm install bunyan or npm install express-bunyan-logger bunyan.
error TypeError: app.use is not a function
cause You are attempting to use `app.use()` on an object that is not an Express application instance, or `app` is undefined.
fix
Ensure app is correctly initialized as const app = express(); and that express is imported: const express = require('express');.
error TypeError: req.log is undefined
cause The `express-bunyan-logger` middleware has not been applied to the request pipeline before the code attempting to access `req.log`.
fix
Ensure app.use(require('express-bunyan-logger')()); is placed early in your Express middleware stack, before any routes or other middleware that rely on req.log.
error No logs appear in console/file despite middleware being active.
cause The underlying Bunyan logger might not have correctly configured streams, or its log level is too high for the messages being emitted.
fix
When initializing express-bunyan-logger (or the underlying Bunyan logger), ensure streams are configured, e.g., streams: [{ level: 'info', stream: process.stdout }], and that the level matches or is lower than the messages you expect to see.
breaking The `express-bunyan-logger` package is no longer actively maintained by its original author. The maintainer explicitly stated a lack of spare time for module maintenance, inviting others to take over. This implies that new features, bug fixes, and security updates are unlikely to be released.
fix Consider migrating to a more actively maintained logging middleware for Express (e.g., `pino-http`, `morgan` with `winston`/`pino`), or be prepared to fork and maintain the library yourself.
gotcha Versions prior to 1.3.3 had known security vulnerabilities related to the `useragent` dependency (#51). While 1.3.3 bumps the dependencies to fix this, using older versions exposes your application.
fix Upgrade to version 1.3.3 or later immediately to address known security vulnerabilities. It's also critical to regularly audit your dependency tree.
gotcha This library is primarily designed for CommonJS (CJS) environments and the README examples exclusively use `require()`. Direct ES Modules (ESM) import is not officially supported and may lead to issues or require CJS interop.
fix Use `require()` syntax for imports. For modern ESM-only projects, consider an alternative logging solution that offers native ESM support.
gotcha The `options.obfuscate` feature, which allows obfuscating nested properties of logged JSON (e.g., passwords in `req.body`), was introduced in version 1.3.0.
fix If you need to obfuscate sensitive data in your logs, upgrade to version 1.3.0 or later and configure the `obfuscate` option in the middleware.
gotcha The `options.immediate` behavior was fixed in v1.2.0. Before this version, when `immediate` was true, it would still log when the response was sent. After v1.2.0, it logs strictly immediately upon request reception.
fix If you rely on `immediate: true` to log at the precise request reception time, ensure you are on version 1.2.0 or higher. For older versions, the log might still be delayed until response is sent, potentially affecting response time calculations.
npm install express-bunyan-logger
yarn add express-bunyan-logger
pnpm add express-bunyan-logger

This quickstart demonstrates setting up `express-bunyan-logger` for both request and error logging within an Express application. It shows how to pass a custom Bunyan logger instance, configure a custom format string, implement a `levelFn` for dynamic log levels, and utilize the `obfuscate` option for sensitive data. It also highlights how to access the request-specific child logger (`req.log`) within subsequent middleware.

const express = require('express');
const expressBunyanLogger = require('express-bunyan-logger');
const bunyan = require('bunyan');

const app = express();
const PORT = process.env.PORT || 3000;

// Create a Bunyan logger instance if you want custom streams or serializers
const customBunyanLogger = bunyan.createLogger({
  name: 'my-express-app',
  streams: [
    { level: 'info', stream: process.stdout },
    { level: 'error', path: './app-errors.log' }
  ],
  serializers: bunyan.stdSerializers
});

// Use the request logger middleware with custom options
app.use(expressBunyanLogger({
  name: 'request-logger',
  logger: customBunyanLogger, // Use the custom bunyan logger
  format: ":remote-address - :user-agent[major] custom logger - :method :url",
  levelFn: function(status) {
    if (status >= 500) return 'error';
    if (status >= 400) return 'warn';
    return 'info';
  },
  obfuscate: ['req.body.password', 'req.headers.authorization'] // Obfuscate sensitive fields
}));

// Middleware to add custom data to the request log
app.use(function(req, res, next) {
  // Access the child logger attached to req
  req.log.info({ customField: 'someValue', userId: 'user123' }, 'Request processed by custom middleware');
  next();
});

app.get('/', (req, res) => {
  req.log.info('Handling GET / request');
  res.send('Hello World!');
});

app.post('/data', express.json(), (req, res) => {
  req.log.info({ body: req.body }, 'Received data post');
  if (req.body.password) {
    req.log.warn('Password received in request body, should be obfuscated.');
  }
  res.status(200).json({ message: 'Data received', received: req.body });
});

// Use the error logger middleware after all routes and other middleware
app.use(expressBunyanLogger.errorLogger({
  name: 'error-logger',
  logger: customBunyanLogger,
  level: 'error'
}));

// Basic error handling middleware
app.use((err, req, res, next) => {
  customBunyanLogger.error(err, 'Unhandled error caught by final error handler');
  res.status(500).send('Something broke!');
});

app.listen(PORT, () => {
  customBunyanLogger.info(`Server listening on port ${PORT}`);
});