Skip to content

KTH/skog

Repository files navigation

Add context to your Node.js logs

Forest photo by Gustav Gullstrand on Unsplash

Getting started

Skog is a opinionated logging library built on top of Pino.

npm install skog
import log, { initializeLogger } from "skog";

initializeLogger();
setFields({ app: "my-app" });
log.info("Hello world");

If your app uses Express, use skogMiddleware to add req_id to every log line.

import log, { initializeLogger, skogMiddleware, setFields } from "skog";
import express from "express";

const app = express();

const app = express();
app.use(skogMiddleware);
app.get("/", () => {
  // This will log "req_id" automatically! You don't need to do anything else!
  log.info("Logging a message");
});

initializeLogger();
setFields({ app: "demo" });
app.listen(3000, () => {
  log.info("Starting server");
});

Recipes

skog exports more functions so you can create your own middleware. For example, if you want to add your own fields or if you want to create middleware for other frameworks.

Add other fields

Example: add a "session_id" field in your logs

import { runWithSkog } from "skog";
import { nanoid } from "nanoid";

function myMiddleware(req, res, next) {
  // Assuming that "req.session.id" exists...
  runWithSkog({ req_id: nanoid(), session_id: req.session.id.slice(-3) }, next);
}

Middleware for other frameworks

As you can see from the example above, runWithSkog accepts two arguments: an object with fields and a function. runWithSkog will return the same thing as returned by the function.

So, you can create a middleware for Next.js:

import { NextResponse } from "next/server";
import { nanoid } from "nanoid";

function middleware(req: NextRequest, ev: NextFetchEvent) {
  return runWithSkogContext(
    {
      session_id: req.cookies["session_id"]?.slice(-3),
      req_id: nanoid(),
    },
    NextResponse.next
  );
}