Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Serialization and Performance

Logging with Pino in Fastify

Use Fastify's built-in Pino logger well: log levels, structured fields, child loggers, request IDs, redacting secrets, serializers and pretty output for development.

When something goes wrong in production you will not have a debugger. You will have logs. Good logs answer four questions fast: what happened, to which request, when, and how bad it was. Fastify ships with Pino, a logger that writes one JSON object per line, built to be cheap on CPU. Turn it on with logger: true, and every request gets an "incoming request" and a "request completed" line automatically.

This lesson explains the shape of Pino output, the level scheme, child loggers and request IDs, and how to keep secrets out of your logs.

Neither Fastify nor Pino is installed on this site. The first example is a small stand-in logger that copies Pino's output format and its level, child and redact ideas; the second connects it to the stand-in framework from The Fastify Request Lifecycle. Real Pino adds worker-thread transports, many serializers and much better speed.

What Pino output looks like

Each log call becomes one line of JSON with a numeric level, a timestamp, process info, the fields you pass and a msg:

JSON
{"level":30,"time":1718000000000,"pid":4120,"hostname":"web-1","reqId":"req-1","msg":"user created"}

Machines love this: log platforms (Loki, Datadog, Elastic, CloudWatch) index each field, so you can search reqId:"req-1" or level>=50 instead of grepping prose.

The levels are numbers so comparisons are cheap:

Level Number Use for
trace 10 Very detailed internals
debug 20 Developer diagnostics
info 30 Normal events (the default)
warn 40 Unexpected but handled situations
error 50 Failures that need attention
fatal 60 The process cannot continue

Setting level: 'warn' hides everything below 40. Disabled calls are close to free, so you can leave debug lines in the code and raise the level in production.

Child loggers and bindings

A child logger carries extra fields on every line it writes. Fastify creates one per request with the request ID, so every message from request.log can be tied to that request without you passing the ID around. You can add your own bindings: request.log.child({ userId }).

Here is a miniature version that behaves like Pino for levels, bindings and redaction.

Node.js A mini Pino: levels, child loggers, redaction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The debug call prints nothing; the child logger repeats reqId and userId on every line; the final line shows the authorization header and password replaced by [Redacted]. That redaction is the most important feature to configure in production.

Fastify's logger options

In real Fastify you pass logger options instead of building a logger yourself:

JavaScript
// real Fastify
const app = Fastify({
  logger: {
    level: process.env.LOG_LEVEL ?? 'info',
    redact: ['req.headers.authorization', 'req.headers.cookie', 'body.password'],
    serializers: {
      req(request) { return { method: request.method, url: request.url, id: request.id }; },
    },
  },
});
  • redact removes sensitive values before they are written. List every path that can carry credentials: Authorization, cookies, passwords, tokens, card numbers.
  • serializers control how objects (req, res, err) become JSON. The default req serializer logs method, URL, host and remote address, but not headers or body, which is a sensible default.
  • transport sends logs through a worker thread. In development use pino-pretty for readable colored lines; in production keep raw JSON and let your platform collect stdout.
  • genReqId sets how request IDs are produced. Reusing a header from your gateway lets one ID follow a request across services.
  • disableRequestLogging: true turns off the automatic "incoming request" and "request completed" lines, if you log those yourself.

You can also give Fastify a logger object you already have, as long as it has the methods Pino has (info, error, debug, fatal, warn, trace, child) using the loggerInstance option.

One request, one story

The real power appears when each log line carries the request ID. A handler uses request.log, and the line is already linked to the request:

Node.js Request-scoped logging with a request ID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Search the output for req-2, and you get the whole failed request in order: arrival, the lookup, completion with status 404. In production, the same story is one filter away in your log platform.

Logging rules that save you later

  1. Log events, not prose. Prefer log.info({ orderId, total }, 'order placed') over string concatenation. Fields can be searched and charted.
  2. Pick levels deliberately. A 404 caused by a client is not an error. Keep error for things you would wake someone up about.
  3. Never log secrets. Redact by path, and avoid logging whole request bodies. Personal data (emails, addresses) deserves the same care.
  4. Log errors as objects (log.error({ err }, 'message')) so the stack trace is serialized properly.
  5. Do not log inside tight loops. Each line costs CPU and disk.
  6. Write to stdout. Let the platform (Docker, systemd, Kubernetes) collect and rotate logs; do not write files from the app.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Pino writes each log entry as:

    One JSON object per line is easy to stream, store and index in log platforms.
  2. 2. What does a child logger add?

    Bindings are merged into every entry from that logger. Fastify creates one per request so lines carry the request ID.
  3. 3. Which option prevents Authorization headers from appearing in logs?

    redact lists paths whose values are censored before the line is written.
  4. 4. With level set to warn, which call still writes a line?

    warn is 40. Only levels with a number of 40 or more (warn, error, fatal) are written.
  5. 5. Where should a production app send its logs?

    Writing to stdout keeps the app simple; Docker, systemd or Kubernetes collect and rotate the stream.

Summary

  • Fastify uses Pino: one JSON line per event with a numeric level, timestamp, bindings and message.
  • request.log is a child logger that carries the request ID, so a whole request can be traced.
  • Configure level, redact, serializers and genReqId; use pino-pretty only in development.
  • Log structured events at deliberate levels, never secrets, and always to stdout.

Next: Caching, ETags and Compression