← Back to Node.js, page 4

nodejs-0074 · Medium mid

Why use structured (JSON) logging, and how do log levels, child loggers and redaction work in Pino?

Structured logs are one JSON object per line with fields such as level, time, message and request id, so tools can search and aggregate them. Pino writes them fast to stdout. Levels filter noise, child loggers add fixed fields (like requestId) to every line, and redact paths hide secrets.

Full answer

Text logs ("User 42 logged in from 10.0.0.5") are easy to read but hard to query. A JSON line such as {"level":30,"msg":"login","userId":42,"ip":"10.0.0.5"} can be filtered by any field, counted, graphed and alerted on in tools like Loki, Elasticsearch or CloudWatch.

Pino is a popular logger for Node because it is fast: it does little work in the main thread and writes newline-delimited JSON to stdout (or a destination stream).

Main ideas:

  • Levels: trace (10), debug (20), info (30), warn (40), error (50), fatal (60). The level option sets the minimum. In production use info, and switch to debug for a short time when investigating.
  • Message and fields: logger.info({ userId: 42 }, 'login ok'). Put data in fields, not in the message text, so each message stays constant and is easy to group.
  • Child loggers: const log = logger.child({ requestId }) adds fixed bindings to every line from log. Create one per request.
  • Redaction: redact: ['req.headers.authorization', 'password'] replaces values with [Redacted] (or removes them). This protects secrets that end up in logged objects.
  • Errors: log errors as err: logger.error({ err }, 'payment failed'). Pino has serializers that include type, message and stack.
  • Pretty printing (pino-pretty) is for development only. In production keep raw JSON and let the platform collect it.

General rules: log events, not noise; one line per event; no secrets or personal data; include ids that let you follow a request across services.

javascript
const pino = require('pino');
const { Writable } = require('node:stream');

// Collect the log lines so the example can print them.
const lines = [];
const sink = new Writable({
  write(chunk, encoding, callback) {
    lines.push(chunk.toString().trim());
    callback();
  },
});

const logger = pino(
  {
    level: 'info',
    base: null,             // no pid and hostname in this demo
    timestamp: false,       // no time, so the output is stable
    redact: ['password', 'headers.authorization'],
    formatters: { level: (label) => ({ level: label }) }, // "info" instead of 30
  },
  sink,
);

logger.debug('this line is below the info level and is dropped');
logger.info({ userId: 42 }, 'login ok');

// One child logger per request adds the same field to every line.
const requestLog = logger.child({ requestId: 'req-7' });
requestLog.info({ route: '/marks', ms: 12 }, 'request finished');
requestLog.warn({ password: 'secret123', headers: { authorization: 'Bearer abc', accept: 'json' } }, 'bad payload');
requestLog.error({ err: new RangeError('marks out of range') }, 'validation failed');

for (const line of lines) {
  const entry = JSON.parse(line);
  if (entry.err) entry.err = { type: entry.err.type, message: entry.err.message }; // hide the stack for a short output
  console.log(JSON.stringify(entry));
}

The debug line is dropped by the level setting. The password and the authorization header are replaced by [Redacted]. Install first with npm install pino (run here with pino 10.4.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): {"level":"info","userId":42,"msg":"login ok"} {"level":"info","requestId":"req-7","route":"/marks","ms":12,"msg":"request finished"} {"level":"warn","requestId":"req-7","password":"[Redacted]","headers":{"authorization":"[Redacted]","accept":"json"},"msg":"bad payload"} {"level":"error","requestId":"req-7","err":{"type":"RangeError","message":"marks out of range"},"msg":"validation failed"}

Key points

  • One JSON object per line makes logs searchable.
  • Levels set how much is written.
  • Child loggers add context such as requestId.
  • Redaction hides secrets.
  • Pretty printing is for development only.

Common mistakes

  • Putting variable data into the message text so lines cannot be grouped.
  • Logging full request bodies, tokens or personal data.
  • Using pino-pretty in production.
  • Creating a new logger per call instead of using child loggers.

Follow-ups

  • How does Pino stay fast?
  • How would you change the log level without a restart?
  • How do you correlate logs across microservices?

Tips

  • Show a JSON line and say what a query on it could do.
  • Name the six levels.
  • Mention redaction as a security feature.