or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-koa-logger

Logging middleware for koa

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/koa-logger@4.0.x

To install, run

npx @tessl/cli install tessl/npm-koa-logger@4.0.0

index.mddocs/

koa-logger

Development-style logging middleware for Koa.js applications that provides colorized HTTP request and response logging with customizable output formatting.

Package Information

  • Package Name: koa-logger
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install koa-logger

Core Imports

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

For ES modules:

import logger from 'koa-logger';

Basic Usage

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

const app = new Koa();

// Basic logging with default console output
app.use(logger());

// The middleware will log requests and responses like:
//   <-- GET /users
//   --> GET /users 200 125ms 1.2kb

Architecture

koa-logger is built around several key components that work together to provide comprehensive HTTP request/response logging:

  • Middleware Factory: Main koaLogger() function that configures and returns the actual middleware
  • Print System: Configurable output transport that handles both console logging and custom transporters
  • Color Mapping: Status code color system using chalk for terminal output (1xx/2xx=green, 3xx=cyan, 4xx=yellow, 5xx=red, etc.)
  • Timing Engine: Request timing measurement with support for legacy request-received integration
  • Stream Counter: Length calculation for streaming responses using passthrough-counter when Content-Length is unavailable
  • Response Monitoring: Uses on-finished to detect response completion, close events, and downstream errors
  • Error Handler: Catches and logs middleware errors while preserving original error propagation

The middleware wraps all downstream middleware to capture request start time, logs the incoming request immediately, then waits for response completion to log the final result with timing and size information.

Capabilities

Logger Middleware Factory

Creates a Koa middleware function that logs HTTP requests and responses with colored output format.

/**
 * Creates a logging middleware for Koa applications.
 * @param {Function|Object} [options] - Either a transporter function or options object
 * @returns {Function} - Koa middleware function with signature async (ctx, next) => {}
 */
function logger(options);

Parameters:

  • options (optional): Can be either:
    • Function: Custom transporter function (str, args) => void
    • Object: Configuration object with transporter property

Options Object:

interface LoggerOptions {
  /** Custom transport function for redirecting log output */
  transporter?: (str: string, args: any[]) => void;
}

Transporter Function:

/**
 * Custom transport function for handling log output
 * @param {string} str - Formatted output string with ANSI colors
 * @param {Array} args - Raw arguments array [format, method, url, status, time, length]
 */
type TransporterFunction = (str: string, args: any[]) => void;

Returns: Async middleware function with signature async (ctx, next) => Promise<void>

Usage Examples:

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

const app = new Koa();

// Basic usage with default console.log output
app.use(logger());

// Custom transporter function (direct function parameter)
app.use(logger((str, args) => {
  // str contains formatted string with colors
  // args contains [format, method, url, status, time, length]
  console.log('Custom:', str);
  // Log to file, external service, etc.
}));

// Custom transporter using options object
app.use(logger({
  transporter: (str, args) => {
    // Custom logging logic
    fs.appendFileSync('access.log', str + '\n');
  }
}));

Log Output Format

The logger produces two types of output:

Request Logging

Shows incoming requests with format: <-- METHOD URL

<-- GET /api/users
  <-- POST /api/login

Response Logging

Shows completed responses with format: INDICATOR METHOD URL STATUS TIME LENGTH

--> GET /api/users 200 45ms 2.1kb
  --> POST /api/login 401 12ms 156b
  xxx GET /api/error 500 234ms -      (for errors)
  -x- GET /api/timeout 200 5000ms 1kb (for closed connections)

Status Code Color Coding:

  • 1xx, 2xx: Green (success)
  • 3xx: Cyan (redirection)
  • 4xx: Yellow (client error)
  • 5xx: Red (server error)
  • 7xx: Magenta (non-standard)
  • 8xx+: Yellow (fallback)

Response Indicators:

  • -->: Normal response completion (gray)
  • xxx: Error occurred during processing (red)
  • -x-: Connection was closed before completion (yellow)

Advanced Features

Stream Length Calculation

The middleware automatically calculates content length for streaming responses by intercepting streams with a counter, providing accurate byte counts even when Content-Length header is not set.

Error Handling

Catches and logs downstream middleware errors while preserving the original error for upstream handling. Errors are displayed with xxx indicator and red coloring.

Request Timing Compatibility

Supports deprecated request-received timing injection for more accurate performance measurements (shows deprecation warning when used).

Timing Display Format

  • < 10 seconds: Displayed in milliseconds (e.g., 245ms)
  • ≥ 10 seconds: Displayed in seconds (e.g., 15s)

Content Length Formatting

  • Uses human-readable byte formatting (e.g., 1.2kb, 156b, 2.1mb)
  • Shows empty string for 204, 205, 304 status codes (no content)
  • Shows - when length cannot be determined (errors, closed connections)

Compatibility

  • Node.js: >= 18
  • Koa: Compatible with Koa v3.0.0+
  • request-received: Legacy timing compatibility (deprecated)

Usage Notes

  • Recommended to use this middleware near the top of your middleware stack to wrap all subsequent middleware
  • The middleware uses on-finished to detect response completion, ensuring accurate timing even for streaming responses
  • All log output includes ANSI color codes for terminal display
  • Custom transporters receive both the formatted color string and raw argument array for flexible processing