Logging with Koa in Logtail

Install the following @logtail/koa NPM package and then attach the Logtail instance as a middleware to your Koa instance:

npm install @logtail/koa
Copied!
const Koa = require("koa");
const { Logtail } = require("@logtail/koa");

// Create a new Koa instance
const koa = new Koa();

// Create a new Logtail client
const logtail = new Logtail("<source-token>");

// Attach Koa to enable HTTP request logging
logtail.attach(koa);
Copied!
warning

Don't forget to replace with your actual source token which you can find by going to your account -> sources -> edit.

How the middleware works

Successful requests

A successful request is one that returns a non-4xx or 5xx status code and doesn't throw any uncaught errors while handling the requests. These are logged to Logtail using [LogLevel.Info](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel)

4xx status codes

These are not considered errors but warnings and log with the same message using [LogLevel.Warn](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel)

5xx status codes

Responses that contain a 5xx status code are considered errors and are logged with [LogLevel.Error](https://github.com/logtail/logtail-js/tree/master/packages/types#loglevel)

Additional logging

Since this Koa plugin extends the regular [@logtail/node](https://github.com/logtail/logtail-js/tree/master/packages/node) logger, you can use the .log|info|warn|error functions as normal to handle logging anywhere in your app.