Fastify Pino Structured Request Logging
Wire Fastify to Pino for structured request logging with redaction, request ids, sampling, and slow-request warnings under load.
Code
import Fastify from 'fastify';
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL ?? 'info',
genReqId: (req) => req.headers['x-request-id'] ?? crypto.randomUUID(),
redact: {
paths: ['req.headers.authorization', 'req.headers.cookie', '*.password'],
censor: '[REDACTED]',
},
serializers: {
res(reply) {
return { statusCode: reply.statusCode, responseTime: reply.elapsedTime };
},
},
transport: { target: 'pino-pretty', options: { colorize: true } },
},
});
app.addHook('onResponse', async (request, reply) => {
if (reply.elapsedTime > 1000) {
request.log.warn({ url: request.url }, 'slow request');
}
});
app.get('/health', async () => ({ status: 'ok' }));
await app.listen({ port: 3000, host: '0.0.0.0' });What the code does
Await points sequence the asynchronous work; a rejection lands at the awaiting line.
Module-level bindings hold the data — app — with no function scope in between.
Environment variables LOG_LEVEL drive configuration, so one artifact serves every environment.
Emits through the .warn level methods with structured payloads, so downstream transports can route by level and field.
The result comes back as an object carrying statusCode.
Points of care
- Plan for an install step:
fastifyis a real dependency, resolved by the package manager. - Uses
crypto, so it needs a browser context — it will not run as-is in Node without shims.
Using it
The call returns statusCode.
Key statements
return { statusCode: reply.statusCode, responseTime: reply.elapsedTime };
app.addHook('onResponse', async (request, reply) => {
if (reply.elapsedTime > 1000) {
request.log.warn({ url: request.url }, 'slow request');
}
});
app.get('/health', async () => ({ status: 'ok' }));
Interactive Tools for This Topic
HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does this need from the package registry?
- These are real dependencies: `fastify`. Without it the snippet will not load.
- What does the code return?
- An object carrying `statusCode`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.