PailFramework MiddlewareHono

Hono

Request-scoped wide event logging middleware for Hono

Last updated:

Hono Middleware

The Hono adapter attaches a request-scoped Wide Event to the Hono context. The event auto-emits when the handler completes or throws.

Setup

import { Hono } from "hono";
import { createPail } from "@visulima/pail";
import { pailMiddleware } from "@visulima/pail/middleware/hono";

const app = new Hono();
const logger = createPail();

app.use("*", pailMiddleware({ pail: logger }));

Accessing the Logger

Via c.get("log")

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

Via useLogger(c)

A typed helper that retrieves the logger from context and throws if the middleware isn't registered:

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

app.get("/api/users", (c) => {
    const log = useLogger(c);
    log.set({ user: { id: 1 } });
    return c.json({ ok: true });
});

Note: Unlike other adapters, Hono's useLogger() requires the context argument c. Hono stores the logger on the context object rather than in AsyncLocalStorage.

How It Works

  1. The middleware creates a WideEvent with request method, path, headers, and request ID
  2. The logger is stored on the Hono context via c.set("log", logger)
  3. The handler runs inside a try/catch:
    • Success: emits with c.res.status
    • Error: emits with the error, then re-throws

Error Handling

Errors are caught, logged, and re-thrown so Hono's error handling pipeline still works:

app.get("/api/fail", async (c) => {
    const log = useLogger(c);
    log.set({ user: { id: 1 } });
    throw new Error("Something went wrong");
    // Wide event emits with error before Hono's onError handles it
});

Route Configuration

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

TypeScript

import type { PailHonoContext } from "@visulima/pail/middleware/hono";

app.get("/api/users", (c: PailHonoContext) => {
    const log = c.get("log");
    log.set({ user: { id: 1 } });
    return c.json({ ok: true });
});

Exported Types

ExportDescription
pailMiddlewareFactory function returning Hono middleware
useLoggerRetrieve logger from Hono context (c required)
PailHonoContextHono context type
PailHonoNextHono next function type
PailHonoMiddlewareThe middleware function signature
HonoMiddlewareOptionsOptions type for pailMiddleware()
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