Logging middleware for koa
npx @tessl/cli install tessl/npm-koa-logger@4.0.0Development-style logging middleware for Koa.js applications that provides colorized HTTP request and response logging with customizable output formatting.
npm install koa-loggerconst logger = require('koa-logger');For ES modules:
import logger from 'koa-logger';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.2kbkoa-logger is built around several key components that work together to provide comprehensive HTTP request/response logging:
koaLogger() function that configures and returns the actual middlewarerequest-received integrationon-finished to detect response completion, close events, and downstream errorsThe 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.
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:
(str, args) => voidtransporter propertyOptions 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');
}
}));The logger produces two types of output:
Shows incoming requests with format: <-- METHOD URL
<-- GET /api/users
<-- POST /api/loginShows 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:
Response Indicators:
-->: Normal response completion (gray)xxx: Error occurred during processing (red)-x-: Connection was closed before completion (yellow)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.
Catches and logs downstream middleware errors while preserving the original error for upstream handling. Errors are displayed with xxx indicator and red coloring.
Supports deprecated request-received timing injection for more accurate performance measurements (shows deprecation warning when used).
245ms)15s)1.2kb, 156b, 2.1mb)- when length cannot be determined (errors, closed connections)on-finished to detect response completion, ensuring accurate timing even for streaming responses