Fastify Pino Structured Request Logging

Wire Fastify to Pino for structured request logging with redaction, request ids, sampling, and slow-request warnings under load.

JavascriptNodeResilience

Code

snippet
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' });