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.
npm install bunyan-middlewareVerified import paths — ran on the pinned version, not inferred.
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`.
For TypeScript, use `import bunyanMiddleware = require('bunyan-middleware')`. For ESM-only JavaScript, consider using a CommonJS wrapper or a bundler that correctly handles CommonJS modules.Always pass an initialized Bunyan logger instance to the `bunyanMiddleware` options, e.g., `logger: bunyan.createLogger({ name: 'my-app' })`.Ensure that if you provide custom `req` serializers, they correctly reference `req.originalUrl` or the desired URL property for accurate logging in mounted Express applications.
In TypeScript or CommonJS, use `const bunyanMiddleware = require('bunyan-middleware')`. If forced to use ESM `import` in a modern Node.js environment, ensure your `tsconfig.json` or bundler settings handle CommonJS imports correctly, or wrap `require` in a utility function.Verify that the header names in the `obscureHeaders` array exactly match the casing of the incoming HTTP headers. Double-check that `bunyan-middleware` is applied early in your middleware stack to obscure headers before other logging mechanisms capture them.