Koa Logger Middleware

4.0.0 · active · verified Wed Apr 22

Koa-logger is a development-style logging middleware for Koa.js applications, providing colorful, concise HTTP request and response logging to the console. The current stable version, 4.0.0, was released after a period of lower activity, signaling a revival of the project and bringing support for Koa v3 and Node.js versions 18 and higher. It outputs request method, URL, response status, duration, and content length, often formatted with ANSI colors for readability. A key differentiator is its customizable `transporter` option, which allows developers to redirect log output to alternative pipes or logging systems, rather than just `process.stdout`. While primarily a CommonJS package, its updates ensure compatibility with modern Node.js environments and Koa framework versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a basic Koa application and integrate `koa-logger` as the primary logging middleware, showing its effect on console output for various HTTP requests.

const Koa = require('koa');
const logger = require('koa-logger');

const app = new Koa();

// Use koa-logger middleware as early as possible to wrap all subsequent middleware
app.use(logger());

// Example middleware to handle requests
app.use(async (ctx, next) => {
  if (ctx.path === '/') {
    ctx.body = 'Hello, Koa-logger!';
  } else if (ctx.path === '/users') {
    ctx.body = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
  } else {
    ctx.status = 404;
    ctx.body = 'Not Found';
  }
  await next(); // Pass control to subsequent middleware
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Koa server running on http://localhost:${port}`);
});

// To run this:
// 1. npm install koa koa-logger
// 2. node your-file-name.js
// 3. Open http://localhost:3000 or http://localhost:3000/users in your browser.

view raw JSON →