{"id":17737,"library":"koa-bunyan-logger","title":"Koa Bunyan Logger Middleware","description":"Koa-bunyan-logger is a Koa middleware designed for integrating structured logging into Koa v2.x applications, leveraging the popular Bunyan logging library. The current stable version is 2.1.0. While its release cadence has been infrequent, updates typically coincide with significant Koa version shifts or critical bug fixes. This library aims to be flexible and lightweight, allowing applications to customize logging behavior without excessive overhead. A key differentiator is its ability to provide flexible log context, request logging, and explicit support for ignoring specific paths, ensuring that only relevant requests generate log entries. It allows passing an existing Bunyan logger instance or creating a new one with options, and handles request IDs for tracing. It provides middleware specifically for setting request context and logging request/response cycles, including duration and status-based log levels. This package is built on CommonJS but can be imported into ESM projects via interop.","status":"active","version":"2.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/koajs/bunyan-logger","tags":["javascript","koa","bunyan","logging","middleware"],"install":[{"cmd":"npm install koa-bunyan-logger","lang":"bash","label":"npm"},{"cmd":"yarn add koa-bunyan-logger","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-bunyan-logger","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency; it's a middleware specifically for Koa v2.x applications.","package":"koa","optional":false},{"reason":"Core logging library used for structured logging functionality.","package":"bunyan","optional":false}],"imports":[{"note":"The primary export is a function. For ESM, use a default import with interop. Attempting to use a named import for 'koaBunyanLogger' will typically result in an undefined value.","wrong":"import { koaBunyanLogger } from 'koa-bunyan-logger';","symbol":"koaBunyanLogger","correct":"import koaBunyanLogger from 'koa-bunyan-logger';\n// or in CommonJS:\nconst koaBunyanLogger = require('koa-bunyan-logger');"},{"note":"`requestIdContext` is a static method/property of the main `koaBunyanLogger` export, not a top-level named export. Access it via the default imported object.","wrong":"import { requestIdContext } from 'koa-bunyan-logger';","symbol":"requestIdContext","correct":"import koaBunyanLogger from 'koa-bunyan-logger';\n// ...\napp.use(koaBunyanLogger.requestIdContext());"},{"note":"`requestLogger` is a static method/property of the main `koaBunyanLogger` export, not a top-level named export. Access it via the default imported object.","wrong":"import { requestLogger } from 'koa-bunyan-logger';","symbol":"requestLogger","correct":"import koaBunyanLogger from 'koa-bunyan-logger';\n// ...\napp.use(koaBunyanLogger.requestLogger());"}],"quickstart":{"code":"import Koa from 'koa';\nimport bunyan from 'bunyan';\nimport koaBunyanLogger from 'koa-bunyan-logger';\n\nconst app = new Koa();\n\n// Create a Bunyan logger instance, which koa-bunyan-logger will use\nconst appLogger = bunyan.createLogger({\n  name: 'my-koa-app',\n  level: 'info',\n  serializers: bunyan.stdSerializers\n});\n\n// Apply the main logging middleware with the custom logger instance\napp.use(koaBunyanLogger(appLogger));\n\n// Add middleware for setting a request ID context\napp.use(koaBunyanLogger.requestIdContext());\n\n// Add middleware for logging request/response cycles\napp.use(koaBunyanLogger.requestLogger({\n  // Example option: ignore specific paths from detailed request logging\n  ignorePath: ['/healthcheck', '/metrics']\n}));\n\n// Custom application middleware to use the logger in a request context\napp.use(async (ctx, next) => {\n  ctx.log.info('Received request from %s for %s', ctx.request.ip, ctx.path);\n  await next();\n  // Note: 'x-response-time' header might need to be set by another middleware if desired\n  ctx.log.info({ status: ctx.status }, 'Handled request for %s', ctx.path);\n});\n\n// Simple route handling\napp.use(async (ctx) => {\n  if (ctx.path === '/healthcheck') {\n    ctx.body = 'OK';\n  } else {\n    ctx.body = 'Hello World';\n  }\n});\n\n// IMPORTANT: Disable Koa's default error handler to prevent raw stack traces\napp.on('error', () => {});\n\nconst PORT = process.env.PORT ?? 8000;\napp.listen(PORT, () => {\n  console.log(`Server listening on http://localhost:${PORT}`);\n  console.log('To view structured logs, pipe output to bunyan CLI: node yourfile.js | npx bunyan -o short');\n});","lang":"typescript","description":"This quickstart demonstrates setting up a Koa v2 application with `koa-bunyan-logger`. It shows how to initialize the logger, apply request ID context and request/response logging middleware (including path ignoring), use `ctx.log` within custom middleware, and properly configure Koa's error handling for structured logs. The code uses modern ESM syntax."},"warnings":[{"fix":"Ensure your Koa application is running version 2.x or later. If you must use Koa v1.x, downgrade `koa-bunyan-logger` to a v1.x release.","message":"Version 2.0.0 and above of `koa-bunyan-logger` are specifically designed for Koa v2.x applications. Attempting to use these versions with Koa v1.x will lead to compatibility issues.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Review and update any custom log field accesses to use properties available on the native Node.js `req` and `res` objects.","message":"Starting with version 1.2.0, the `req` and `res` objects passed to the logger context changed from Koa's wrapper objects (`this.request`, `this.response`) to the native Node.js HTTP objects (`this.req`, `this.res`). This alters the available properties for logging (e.g., `res.statusCode` instead of `res.status`).","severity":"breaking","affected_versions":">=1.2.0"},{"fix":"Add `app.on('error', () => {});` to your Koa application's initialization code to suppress the default error logging.","message":"Koa's default error handler will log raw error stack traces to `stderr` in a non-JSON format, which can interfere with structured logging. It is strongly recommended to disable it.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Adopt the pattern `import koaBunyanLogger from 'koa-bunyan-logger';` followed by `app.use(koaBunyanLogger.requestLogger());` instead of attempting named imports like `import { requestLogger } from 'koa-bunyan-logger';`.","message":"`koa-bunyan-logger` uses CommonJS module exports. When used in an ESM project, ensure you use the default import (`import koaBunyanLogger from 'koa-bunyan-logger';`) and access sub-middlewares as properties (`koaBunyanLogger.requestLogger()`), as direct named imports are not supported.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure Koa is initialized correctly for v2.x: change `const app = koa();` to `const app = new Koa();`","cause":"This error often occurs when initializing a Koa v2+ application using `koa()` instead of `new Koa()`. `koa-bunyan-logger` targets Koa v2.x.","error":"TypeError: app.use is not a function"},{"fix":"Run your Node.js application and pipe its output to the `bunyan` command-line tool. For example: `node your_app.js | npx bunyan -o short`.","cause":"Bunyan outputs logs as structured JSON by default. To make them human-readable, you need to pipe your application's output through the Bunyan CLI formatter.","error":"Application logs appear as raw JSON objects in the console, instead of a human-readable format."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}