Logging in Node with Pino

Intermediate · 34 min

Structured JSON logging in Node with Pino, covering levels, child loggers, redaction, error serialization, transports and request logging with pino-http.

Before thisConfiguration and environment variablesExpress routing and middleware

Better Stack · 42 min · from 1:18

Logging in Node with Pino

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Better StackReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Pino writes one JSON object per line to stdout and keeps the work off the hot path. In production you ship those lines to a log system, and in development you pipe them through `pino-pretty`.
  • Levels are `trace`, `debug`, `info`, `warn`, `error` and `fatal`. Set the threshold from an environment variable such as `LOG_LEVEL`, and anything below it costs almost nothing.
  • Put data in an object first and the message second: `logger.info({ userId: 42 }, 'user signed in')`. Fields become searchable keys, and the message stays a constant string you can group on.
  • Log errors with `logger.error({ err }, 'message')` or pass the `Error` as the first argument. Pino serializes `type`, `message` and `stack` for you.
  • `logger.child({ requestId })` returns a logger that adds those fields to every line it writes, which is how one request's lines are tied together.
  • `redact: ['password', 'req.headers.authorization']` replaces secret fields with `[Redacted]` before output. List the paths you know about, since redaction is only as good as the list.
  • Transports move formatting and shipping into a separate worker thread, so slow work like prettifying or sending to a service does not block the event loop. `pino-http` adds one structured log line per request.

Logs are for the person debugging at 3 a.m.

When something breaks in production you cannot attach a debugger. Logs are what you have. A line like Error: something went wrong tells you almost nothing. A line that says which request, which user, which operation, how long it took and the full stack is something you can search and act on.

That is structured logging: each entry is a record with named fields instead of a sentence. The concepts, including correlation ids that tie a request’s lines together, are in structured logging and correlation ids. This lesson is the Node tool. Pino, written by Matteo Collina and used by Fastify, is built to be fast: it writes JSON lines directly and defers anything expensive.

I ran everything below with Pino 10 and pino-http on Node 26. The video was made on Pino 8, and the core API shown there is unchanged.

A first logger

import pino from 'pino';

export const logger = pino({
  level: process.env.LOG_LEVEL ?? 'info',
  base: { service: 'api' },
  timestamp: pino.stdTimeFunctions.isoTime,
  formatters: { level: (label) => ({ level: label }) },
});

logger.debug('hidden at info');
logger.info({ userId: 42 }, 'user signed in');
logger.warn('disk at %d%%', 91);

Each call prints one line of JSON:

{"level":"info","time":"2026-11-21T18:03:11.152Z","service":"api","userId":42,"msg":"user signed in"}

Three things to notice. The debug line printed nothing, because the threshold is info. Setting LOG_LEVEL=debug made it appear. The object comes first and the message second, so userId is a field of its own. And the formatters.level option turned the default numeric level (30) into the label ("info"), which is easier for humans reading raw lines. Without it, Pino logs numbers, as the pino-http example further down does.

Levels, in order of severity, are trace, debug, info, warn, error and fatal. Read the threshold from the environment (see configuration and environment variables), and you can turn up detail on a misbehaving instance without redeploying.

Keep the message a constant. 'user signed in' can be grouped and counted. A message that interpolates the id cannot.

Logging errors

logger.error(new Error('boom'), 'request failed');
logger.error({ err: new Error('boom2') }, 'request failed 2');

Both produced the same shape: an err object with type, message and stack. Pino ships a standard serializer for the err key, so you do not need to stringify anything yourself. Always log the error object itself, not just its message, or you lose the stack.

Child loggers

A server handles many requests at once, so their log lines interleave. To tell them apart, attach an id:

const child = logger.child({ requestId: 'r-1' });
child.info('inside request');
child.info({ step: 2 }, 'still inside');

Both lines carry "requestId":"r-1" along with the parent’s service. Creating a child is cheap, and the idea is the one in the backend lesson: a correlation id that lets you filter the stream down to one request. Passing that child through every function by hand gets tedious, which is the problem AsyncLocalStorage and context propagation solves.

Redaction

const logger = pino({
  redact: { paths: ['req.headers.authorization', 'password', '*.token'], censor: '[Redacted]' },
});
logger.info({ password: 'hunter2', user: { token: 'abc' } }, 'login payload');
// ... "password":"[Redacted]","user":{"token":"[Redacted]"} ...

Pino replaces those paths before the line is written, so the secret never reaches a file or a vendor. It is a safety net, not a policy. It only covers paths you listed, so a new field called apiKey is logged in the clear until someone adds it. The better habit is to log specific fields rather than whole objects. Secrets in logs are a recurring source of breaches, as covered in secrets and sensitive data handling.

Logging requests

pino-http is Express middleware that logs one line per request when the response finishes, and gives each handler req.log, a child logger with the request id.

import express from 'express';
import pino from 'pino';
import pinoHttp from 'pino-http';
import { randomUUID } from 'node:crypto';

const logger = pino({ redact: ['req.headers.authorization', 'req.headers.cookie'] });
const app = express();

app.use(pinoHttp({
  logger,
  genReqId: (req) => req.headers['x-request-id'] ?? randomUUID(),
  customLogLevel: (req, res, err) =>
    err || res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info',
}));

app.get('/hello', (req, res) => { req.log.info('handling hello'); res.send('hi'); });

I sent a request with Authorization: Bearer secret and X-Request-Id: abc. The handler’s own line and the completion line both carried id: "abc", the header showed [Redacted], and the completion line included the status and a numeric responseTime. A request without the header got a generated UUID, and a 404 logged at warn through customLogLevel. That mix of level-by-status is worth setting, since otherwise every request is info.

Transports and pretty output

Raw JSON is for machines. For development, pipe through the pretty printer:

node app.js | npx pino-pretty

For production, Pino’s recommendation is to write to stdout and let the platform or a log shipper collect it. When you want Pino itself to route output, a transport runs in a separate worker thread, so formatting or network calls don’t block the event loop:

const logger = pino({
  transport: {
    targets: [
      { target: 'pino-pretty', level: 'info' },
      { target: 'pino/file', level: 'error', options: { destination: 'errors.log', mkdir: true } },
    ],
  },
});

I ran this: an info line went only to the pretty target, and an error line went to both, and errors.log held the JSON for the error. Worker threads are explained in worker threads. Pino also ships a few other options, like pino.destination() for fast file writes, and transports exist for services such as Loki and Datadog. One caution: output buffered in a transport can be lost if the process dies abruptly, so flush on shutdown, as discussed in deploying Node applications.

Pino or Winston

Winston is the older, more configurable library. It has many transports and a flexible API, at the cost of speed and more setup. Pino is leaner, with JSON as the default and performance as the design goal. For a new service Pino is the usual choice. If you inherit Winston, the principles here still apply.

What the video covers

The embedded clip, from 1:18 to 35:15 of Better Stack’s Pino deep-dive, covers installing Pino, creating a logger, pino-pretty, custom levels, the default level and level from an environment variable, formatters, custom output, child loggers, logging errors, transports, redaction and using Pino in Fastify. That is nearly everything above except request logging with pino-http in Express. The clip skips the 78-second intro and the last chapter, which is a Better Stack product demo. At 34 minutes, it is long. The original video is from November 2023, on Pino 8, and transcripts were not available, so I’m describing it from its chapter list. Better Stack is a log-management vendor. The Express request logging, the err serialization details and the Pino 10 behaviour above come from running the code.

Where this fits

Logs tell you what happened. When the question is why a service is slow, you need to measure it: profiling and finding bottlenecks.

Check yourself

  1. 01Why log `logger.info({ userId: 42 }, 'user signed in')` rather than `logger.info('user 42 signed in')`?

    The first writes `userId` as a separate JSON field, so a log system can filter or count by it. The second buries the id inside a string that has to be parsed with a regex, and every message differs, which makes grouping impossible. A constant message plus structured fields is the core of structured logging.

  2. 02You set `LOG_LEVEL=warn` in production. Which of `info`, `warn` and `error` calls are written?

    Only `warn` and `error`. A level is a threshold: anything at that severity or above is written, and lower levels are skipped without formatting any output. Pino's order is `trace`, `debug`, `info`, `warn`, `error`, `fatal`.

  3. 03How do you stop passwords and `Authorization` headers appearing in logs?

    Configure `redact` with the field paths, for example `['password', '*.token', 'req.headers.authorization']`, and pino replaces them with `[Redacted]` before writing. Also avoid logging whole request bodies or headers by default, because redaction only covers paths you thought of.

  4. 04What problem does a child logger solve in a web service?

    Lines from concurrent requests interleave in the output. A child logger created per request, `logger.child({ requestId })`, stamps every line with that id, so you can filter the stream down to one request. `pino-http` does this for you as `req.log`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark