What is koa-logger?
koa-logger is a middleware for Koa that provides logging capabilities. It logs HTTP requests and responses, including details such as method, URL, status code, and response time. This can be useful for debugging and monitoring purposes.
What are koa-logger's main functionalities?
Basic Logging
This feature allows you to log basic HTTP request and response details. The code sample demonstrates how to set up koa-logger in a Koa application to log incoming requests and outgoing responses.
const Koa = require('koa');
const logger = require('koa-logger');
const app = new Koa();
app.use(logger());
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Custom Logging Format
This feature allows you to customize the logging format. The code sample shows how to use a custom logging function to format the log output according to your needs.
const Koa = require('koa');
const logger = require('koa-logger');
const app = new Koa();
app.use(logger((str, args) => {
console.log(`Custom Log: ${str}`);
}));
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Other packages similar to koa-logger
morgan
Morgan is a popular HTTP request logger middleware for Node.js. It is often used with Express but can be adapted for use with Koa. Morgan provides various predefined logging formats and allows for custom formats, making it versatile for different logging needs.
winston
Winston is a versatile logging library for Node.js that supports multiple transports (e.g., console, file, HTTP). While not specifically designed for Koa, it can be integrated into a Koa application to provide more advanced logging capabilities, such as logging to different destinations and log levels.
bunyan
Bunyan is another powerful logging library for Node.js that provides a JSON-based logging format. It is designed for high-performance logging and can be integrated with Koa to provide structured logs, which are useful for log analysis and monitoring.
koa-logger
Development style logger middleware for koa. Compatible with request-received.
Notice: koa-logger@2
supports koa@2
; if you want to use this module with koa@1
, please use koa-logger@1
.
<-- GET /
--> GET / 200 835ms 746b
<-- GET /
--> GET / 200 960ms 1.9kb
<-- GET /users
--> GET /users 200 357ms 922b
<-- GET /users?page=2
--> GET /users?page=2 200 466ms 4.66kb
Installation
$ npm install koa-logger
Example
const logger = require('koa-logger')
const Koa = require('koa')
const app = new Koa()
app.use(logger())
Notes
Recommended that you .use()
this middleware near the top
to "wrap" all subsequent middleware.
Use Custom Transporter
const logger = require('koa-logger')
const Koa = require('koa')
const app = new Koa()
app.use(logger((str, args) => {
}))
or
app.use(logger({
transporter: (str, args) => {
}
}))
Param str
is output string with ANSI Color, and you can get pure text with other modules like strip-ansi
Param args
is a array by [format, method, url, status, time, length]
License
MIT