Logger
ValidatedA shared Pino logger with request IDs, async context, and Express, Fastify, and Hono adapters.
The logger block gives your app one Pino instance. Each request gets an ID, log lines written during that request include the ID, and the framework adapters log the request method, path, status, and duration after the handler runs.
There is no root index.ts. Import the shared logger from core and adapters from adapters/.
The core uses pino-pretty when NODE_ENV is not production. The CLI installs pino but not pino-pretty. Add it as a dev dependency, or the logger will fail at startup outside production:
pnpm add -D pino-prettyWith npm, run npm install -D pino-pretty.
Quick start
pnpm dlx blockend-cli init
pnpm dlx blockend-cli add loggerimport express from "express";
import { expressLoggerAdapter } from "@/blocks/logger/adapters/express";
import { logger } from "@/blocks/logger/core";
const app = express();
app.use(expressLoggerAdapter);
app.get("/", (_req, res) => {
logger.info("Handling request");
res.json({ ok: true });
});Files
logger/
├── adapters/
│ ├── express.ts
│ ├── fastify.ts
│ └── hono.ts
└── core.tsThe CLI copies core.ts and one adapter. It does not create an index.ts.
Installation
pnpm dlx blockend-cli add loggerThe CLI copies the adapter for your configured framework and installs pino. Add pino-pretty yourself if you want pretty logs in development.
Copy core.ts and the adapter you need into blocks/logger. Install pino. For development logs, also install pino-pretty. With the Fastify adapter, install fastify-plugin as well.
Core
import { pino } from "pino";
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
export interface LoggerContext {
requestId: string;
[key: string]: unknown;
}
export const loggerContext = new AsyncLocalStorage<LoggerContext>();
export function getRequestId(): string | undefined {
return loggerContext.getStore()?.requestId;
}
const isProduction = process.env.NODE_ENV === "production";
export const logger = pino({
level: isProduction ? "info" : "debug",
mixin() {
const store = loggerContext.getStore();
return store ? { requestId: store.requestId } : {};
},
redact: {
paths: ["Authorization", "*.token", "token", "*.password", "password"],
censor: "[REDACTED]"
},
...(isProduction
? {}
: {
transport: {
target: "pino-pretty",
options: {
colorize: true,
translateTime: "SYS:standard",
ignore: "hostname,pid"
}
}
})
});
export function runWithLoggerContext<T>(
incomingId: string | undefined | null,
callback: (requestId: string) => T
) {
const requestId = incomingId || randomUUID();
return loggerContext.run({ requestId }, () => callback(requestId));
}
Express adapter
import type { Request, Response, NextFunction } from "express";
import { logger, runWithLoggerContext } from "../core.js";
interface LoggedRequest extends Request {
id?: string;
}
export function expressLoggerAdapter(req: LoggedRequest, res: Response, next: NextFunction): void {
const rawId = req.headers["x-request-id"]?.toString();
runWithLoggerContext(rawId, (requestId) => {
req.id = requestId;
const start = performance.now();
res.on("finish", () => {
logger.info(
{
http: {
method: req.method,
path: req.path,
statusCode: res.statusCode,
durationMs: Math.round(performance.now() - start)
}
},
`HTTP ${req.method} ${req.path} completed`
);
});
next();
});
}
Fastify adapter
import type { FastifyPluginAsync } from "fastify";
import fp from "fastify-plugin";
import { runWithLoggerContext, loggerContext, logger } from "../core.js";
// Augment Fastify types to natively recognize custom request properties without 'any' casting
declare module "fastify" {
interface FastifyRequest {
requestId: string;
}
}
declare module "http" {
interface IncomingMessage {
_startTime?: number;
}
}
const fastifyLoggerPlugin: FastifyPluginAsync = async (fastify) => {
// Hook 1: Capture incoming request metadata and establish ALS context
fastify.addHook("onRequest", (request, reply, done) => {
const rawId = request.headers["x-request-id"]?.toString();
request.raw._startTime = performance.now();
runWithLoggerContext(rawId, (requestId) => {
request.requestId = requestId;
// Keep the response finish listener tied directly to the execution scope
reply.raw.on("finish", () => {
const start = request.raw._startTime || performance.now();
logger.info(
{
http: {
method: request.method,
path: request.url,
statusCode: reply.statusCode,
durationMs: Math.round(performance.now() - start)
}
},
`HTTP ${request.method} ${request.url} completed`
);
});
done();
});
});
// Hook 2: Re-bind right before running the route handler to shield the context
fastify.addHook("preHandler", (request, _reply, done) => {
const currentId = request.requestId;
if (currentId) {
loggerContext.run({ requestId: currentId }, () => {
done();
});
} else {
done();
}
});
};
export const fastifyLogger = fp(fastifyLoggerPlugin);
Hono adapter
import type { MiddlewareHandler } from "hono";
import { logger, runWithLoggerContext } from "../core.js";
export function honoLoggerAdapter(): MiddlewareHandler {
return async (c, next) => {
const rawId = c.req.header("x-request-id");
const start = performance.now();
// Wrap the next execution flow in your core ALS context
await runWithLoggerContext(rawId, async (requestId) => {
// Attach the generated/incoming ID to Hono's execution context variables
c.set("requestId", requestId);
// Continue processing the request chain
await next();
// Log response details after execution has completed
logger.info(
{
http: {
method: c.req.method,
path: c.req.path,
statusCode: c.res.status,
durationMs: Math.round(performance.now() - start)
}
},
`HTTP ${c.req.method} ${c.req.path} completed`
);
});
};
}
Framework setup
Express
import express from "express";
import { expressLoggerAdapter } from "@/blocks/logger/adapters/express";
const app = express();
app.use(expressLoggerAdapter);The adapter sets req.id, generates a UUID when x-request-id is missing, and logs after res emits finish.
Fastify
import Fastify from "fastify";
import { fastifyLogger } from "@/blocks/logger/adapters/fastify";
const app = Fastify();
await app.register(fastifyLogger);The adapter adds request.requestId and registers onRequest and preHandler hooks. Register it before your routes.
Hono
import { Hono } from "hono";
import { honoLoggerAdapter } from "@/blocks/logger/adapters/hono";
type Variables = {
requestId: string;
};
const app = new Hono<{ Variables: Variables }>();
app.use("*", honoLoggerAdapter());
app.get("/", (c) => {
return c.json({ requestId: c.get("requestId") });
});Declare the requestId variable in your Hono type so c.get("requestId") is typed.
Request context
runWithLoggerContext creates an AsyncLocalStorage scope. The adapters use it for HTTP requests. Use it directly for background jobs and queue workers:
import { logger, runWithLoggerContext } from "@/blocks/logger/core";
await runWithLoggerContext(null, async (requestId) => {
logger.info({ jobId: "job_123", requestId }, "Processing job");
});Pass an existing ID as the first argument to reuse it:
await runWithLoggerContext("job_123", async () => {
logger.info("Processing job");
});getRequestId() returns the current ID or undefined outside a context.
import { getRequestId } from "@/blocks/logger/core";
const id = getRequestId();Configuration
The logger is configured in core.ts, not through a factory. Edit the file to change it:
const isProduction = process.env.NODE_ENV === "production";
export const logger = pino({
level: isProduction ? "info" : "debug",
mixin() {
const store = loggerContext.getStore();
return store ? { requestId: store.requestId } : {};
},
redact: {
paths: ["Authorization", "*.token", "token", "*.password", "password"],
censor: "[REDACTED]"
},
...(isProduction
? {}
: {
transport: {
target: "pino-pretty",
options: {
colorize: true,
translateTime: "SYS:standard",
ignore: "hostname,pid"
}
}
})
});| Setting | Value |
|---|---|
| Level | debug outside production, info in production |
| Request ID field | requestId |
| Redacted fields | Authorization, token, password, and one nested level for token and password |
| Dev transport | pino-pretty |
| Production transport | JSON to stdout |
The redaction list is narrow. Add your own paths if your app logs cookies, API keys, or other secrets.
API reference
logger
A configured pino.Logger. It writes JSON in production and pretty output in development.
logger.info({ userId }, "User signed in");
logger.error({ err }, "Payment failed");getRequestId
function getRequestId(): string | undefined;Returns the request ID from the current async context.
runWithLoggerContext
function runWithLoggerContext<T>(
incomingId: string | undefined | null,
callback: (requestId: string) => T
): T;Uses incomingId when it is a non-empty string. Otherwise it generates a UUID. The callback runs inside the new context.
loggerContext
The AsyncLocalStorage<LoggerContext> instance. Use it only if you need to inspect or replace the store directly.
Adapters
| Adapter | Export | Adds |
|---|---|---|
| Express | expressLoggerAdapter | req.id, response finish log |
| Fastify | fastifyLogger | request.requestId, response finish log |
| Hono | honoLoggerAdapter | c.set("requestId", id), response log |
All adapters read x-request-id when present and generate a UUID otherwise.
Production notes
- Keep JSON logs in production. Pretty printing costs CPU and is harder to parse.
- Ship logs to a collector. stdout alone is not durable on most platforms.
- The adapters log one line per request that returns normally. They do not log request bodies or headers. A request that throws past the Hono adapter does not produce a completion line.
- The incoming
x-request-idheader is trusted. If clients can set it, validate the format before you use it for tracing. - Error objects logged as
{ err }are serialized by Pino with their stack trace. Do not log secrets in error messages.
When not to use it
- You already have a configured Pino, Winston, or OpenTelemetry logger.
- You need distributed tracing. Request IDs are not trace spans. Use OpenTelemetry for that.
- You need audit logs with retention and tamper protection. Use a dedicated audit system.
Related blocks
- Error handler can use the same logger for structured error events.
- Idempotency accepts a logger that matches the
Loggerinterface. - Graceful shutdown can close transports during shutdown if you add a task.