PailFramework MiddlewareFastify

Fastify

Request-scoped wide event logging plugin for Fastify

Last updated:

Fastify Plugin

The Fastify adapter registers lifecycle hooks that attach a request-scoped Wide Event to every request. The event auto-emits on response or error.

Setup

import Fastify from "fastify";
import { createPail } from "@visulima/pail";
import { pailPlugin } from "@visulima/pail/middleware/fastify";

const app = Fastify();
const logger = createPail();

pailPlugin(app, { pail: logger });

app.listen({ port: 3000 });

Accessing the Logger

Via request.log

app.get("/api/users", async (request, reply) => {
    request.log.set({ user: { id: 1 } });
    request.log.info("Fetched user list");
    return { ok: true };
});

Via useLogger()

Access the logger from anywhere in the async call stack:

import { useLogger } from "@visulima/pail/middleware/fastify";

async function fetchUser(id: number) {
    const log = useLogger();
    log.set({ user: { id } });
    log.info("Querying database");
    // ...
}

How It Works

The plugin registers three Fastify hooks:

  1. onRequest — Creates a WideEvent, attaches it to request.log, and enters AsyncLocalStorage context
  2. onResponse — Emits the event with the response status code
  3. onError — Emits the event with the error (prevents double-emit if both fire)

If the route is excluded, the onRequest hook calls done() immediately and no logger is attached.

Request ID

The plugin reads x-request-id from incoming headers. If not present, it generates a UUID. The request ID is included in the emitted wide event.

Route Configuration

pailPlugin(app, {
    pail: logger,
    service: "api-gateway",
    exclude: ["/health", "/metrics"],
    include: ["/api/**"],
    routes: {
        "/api/auth/**": { service: "auth-service" },
    },
});

TypeScript

import type { PailFastifyRequest, PailFastifyReply } from "@visulima/pail/middleware/fastify";

app.get("/api/users", async (request: PailFastifyRequest, reply: PailFastifyReply) => {
    request.log?.set({ user: { id: 1 } });
    return { ok: true };
});

Exported Types

ExportDescription
pailPluginRegister the plugin on a Fastify instance
useLoggerRetrieve logger from AsyncLocalStorage
PailFastifyRequestFastify request with log?: WideEvent
PailFastifyReplyFastify reply type
PailFastifyInstanceFastify instance type with hook registration
FastifyPluginOptionsOptions type for pailPlugin()
WideEventRe-exported WideEvent class
Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues