Express Bunyan Logger Middleware
raw JSON →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.
Common errors
error Error: Cannot find module 'bunyan' ↓
npm install bunyan or npm install express-bunyan-logger bunyan. error TypeError: app.use is not a function ↓
app is correctly initialized as const app = express(); and that express is imported: const express = require('express');. error TypeError: req.log is undefined ↓
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. ↓
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. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install express-bunyan-logger yarn add express-bunyan-logger pnpm add express-bunyan-logger Imports
- expressBunyanLogger wrong
import expressBunyanLogger from 'express-bunyan-logger';correctconst expressBunyanLogger = require('express-bunyan-logger'); - mainLoggerMiddleware wrong
app.use(expressBunyanLogger);correctapp.use(require('express-bunyan-logger')()); - errorLoggerMiddleware wrong
app.use(expressBunyanLogger.errorLogger);correctapp.use(require('express-bunyan-logger').errorLogger()); - requestChildLogger
req.log.debug('this is debug in middleware');
Quickstart
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}`);
});