{"id":17634,"library":"express-requests-logger","title":"Express Request/Response Logger","description":"express-requests-logger is an Express middleware designed for comprehensive logging of incoming HTTP requests and outgoing responses within Node.js applications. The current stable version is 4.0.3, with v4.0.1 released in August 2024, indicating active maintenance though its release cadence can be somewhat irregular. A key differentiator is its extensive configuration options, allowing developers to precisely control what data is logged. This includes masking or excluding sensitive fields from request and response bodies, headers, and query parameters. It also supports integration with custom loggers, although it's primarily tested with Bunyan, and offers a `shouldSkipAuditFunc` for dynamic conditional logging. The `doubleAudit` feature provides flexibility for logging requests both upon arrival and after the response is sent, which can be crucial for debugging systems prone to crashes during request processing.","status":"active","version":"4.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/ugolas/express-request-logger","tags":["javascript","logs","requests","audit","express"],"install":[{"cmd":"npm install express-requests-logger","lang":"bash","label":"npm"},{"cmd":"yarn add express-requests-logger","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-requests-logger","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is an Express.js middleware and requires an Express application to function.","package":"express","optional":false},{"reason":"While not strictly required, the package is tested primarily with Bunyan and its `logger` option is designed for Bunyan-like loggers with an `info` method. Using Bunyan is highly recommended for best compatibility and out-of-the-box configuration.","package":"bunyan","optional":true}],"imports":[{"note":"The package exports a default function. Use a default import for ESM. Incorrectly using named import will result in `TypeError: audit is not a function`.","wrong":"import { audit } from 'express-requests-logger';","symbol":"audit","correct":"import audit from 'express-requests-logger';"},{"note":"The package exports a default function. For CommonJS, `require` directly returns the middleware function. Destructuring will result in an undefined `audit`.","wrong":"const { audit } = require('express-requests-logger');","symbol":"audit","correct":"const audit = require('express-requests-logger');"},{"note":"The middleware expects a single options object as its argument. Passing logger and options separately is incorrect and will cause configuration issues.","wrong":"app.use(audit(myLogger, { request: { maskBody: ['password'] } }));","symbol":"middleware options","correct":"app.use(audit({ logger: myLogger, request: { maskBody: ['password'] } }));"}],"quickstart":{"code":"import express from 'express';\nimport audit from 'express-requests-logger';\nimport bunyan from 'bunyan';\n\nconst app = express();\nconst port = 3000;\n\n// Initialize a Bunyan logger for structured logging\nconst logger = bunyan.createLogger({\n  name: 'my-express-app',\n  level: 'info' // Set default log level\n});\n\n// Add express.json() middleware to parse JSON request bodies\napp.use(express.json());\n\n// Apply the express-requests-logger middleware\napp.use(audit({\n  logger: logger, // Provide the initialized logger\n  doubleAudit: true, // Log once on request arrival, and again after response is sent\n  excludeURLs: ['/health'], // URLs to entirely skip logging for\n  request: {\n    maskBody: ['password', 'creditCardNumber'], // Mask sensitive fields in the request body\n    excludeHeaders: ['authorization'] // Exclude 'Authorization' header from logs\n  },\n  response: {\n    maskBody: ['jwtToken'], // Mask sensitive fields in the response body\n    maxBodyLength: 200 // Limit the length of logged response body content\n  },\n  shouldSkipAuditFunc: (req, res) => {\n    // Example: Skip logging successful responses to /data\n    return req.path === '/data' && res.statusCode === 200;\n  }\n}));\n\n// Define a simple root route\napp.get('/', (req, res) => {\n  logger.info('Received request for root path.');\n  res.status(200).send('Welcome to the API!');\n});\n\n// Define a login route to demonstrate body masking\napp.post('/login', (req, res) => {\n  logger.info('Attempting user login.');\n  const { username, password } = req.body;\n  if (username === 'test' && password === 'secret') {\n    res.status(200).json({ message: 'Login successful', jwtToken: 'a.b.c.123' });\n  } else {\n    res.status(401).json({ message: 'Invalid credentials' });\n  }\n});\n\n// Define a health check route (will be excluded from logs)\napp.get('/health', (req, res) => {\n  res.status(200).send('API is healthy');\n});\n\n// Start the Express server\napp.listen(port, () => {\n  logger.info(`Server listening on port ${port}`);\n});","lang":"typescript","description":"This quickstart sets up a basic Express application with `express-requests-logger` to demonstrate request and response logging. It integrates with Bunyan, enables JSON body parsing, configures sensitive data masking for both request and response bodies, excludes specific headers, and utilizes URL exclusion for health check endpoints. It also includes an example of `shouldSkipAuditFunc` for conditional logging."},"warnings":[{"fix":"Review your logging system's configuration and alerting rules. If you have specific alerts or filters based on log levels, ensure they correctly capture 'ERROR' level messages for 5xx status codes to avoid missing critical alerts. No code changes are typically required in your application.","message":"The log message level for HTTP 5xx status codes has been changed from 'info' to 'ERROR'. This means that server-side errors will now be categorized at a higher severity level in your logs.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade your Node.js runtime environment to version 16 or higher. Node.js 16 is the minimum officially supported version for `express-requests-logger` v4.0.0 and subsequent releases.","message":"Official support for Node.js versions 14 and below has been removed. Running `express-requests-logger` on these older Node.js runtimes is no longer officially supported and may lead to unexpected behavior, compatibility issues, or unpatched vulnerabilities.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"If not using Bunyan, ensure your custom logger provides an `info` method with the signature `(data: object) => void`. You might need to create a simple wrapper function to adapt your logger's API to this expected format.","message":"The `logger` option expects an object with an `info` method that accepts a single object argument for structured logging. While primarily tested with Bunyan, custom loggers must conform to this interface.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Be mindful of log volume when using `doubleAudit`. Configure your log aggregation and analysis tools to handle or de-duplicate these entries if necessary. If you only need logging after the full request-response cycle, set `doubleAudit: false`.","message":"Enabling `doubleAudit: true` causes each request and its corresponding response to be logged twice: once when the request arrives and again after the response is sent. This can significantly increase log volume.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"For ES Modules (ESM), use `import audit from 'express-requests-logger';`. For CommonJS, use `const audit = require('express-requests-logger');`.","cause":"This error typically occurs when the `express-requests-logger` package is imported incorrectly, treating its default export as a named export.","error":"TypeError: audit is not a function"},{"fix":"Ensure that the logger object passed to the `logger` option is correctly initialized and exposes an `info` method, as demonstrated with `bunyan.createLogger()` in the quickstart example.","cause":"The object provided to the `logger` option within the `express-requests-logger` configuration does not have a callable `info` method.","error":"Error: logger.info is not a function"},{"fix":"Ensure that your routes and other middleware do not attempt to send responses or modify headers after `res.send()`, `res.json()`, or `res.end()` has already been called. Always return or use `next()` after sending a response if subsequent middleware should not execute.","cause":"This is a general Express error, but it can sometimes be triggered or exacerbated by middleware if not handled carefully, especially with `doubleAudit` or custom `shouldSkipAuditFunc` that modifies responses without proper checks.","error":"Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}