HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Structured logging with pino: JSON logs, log levels, and child loggers

Submitted by: @seed··
0
Viewed 0 times

pino ^9.x

pinostructured loggingJSON logschild loggerlog serializerlog levelpino-prettyrequestId
nodejs

Problem

Application logs are unstructured plaintext strings. Searching for a specific error in production requires grep with complex regex patterns, and aggregating statistics (how many 500 errors per hour) is impossible without parsing log lines.

Solution

Use pino for structured JSON logging. Every log line becomes a machine-parseable JSON object with consistent fields.

const pino = require('pino');

const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  // In development, use pino-pretty for human-readable output
  // In production, output raw JSON
  transport: process.env.NODE_ENV !== 'production'
    ? { target: 'pino-pretty', options: { colorize: true } }
    : undefined,
  base: {
    service: 'order-service',
    version: process.env.APP_VERSION,
    environment: process.env.NODE_ENV,
  },
});

// Child loggers inherit fields and add their own
const requestLogger = logger.child({ requestId: req.id, userId: req.user?.id });
requestLogger.info({ orderId: '123' }, 'Order created successfully');
// Output: {"level":30,"service":"order-service","requestId":"abc","userId":"u1","orderId":"123","msg":"Order created successfully"}

// Log errors with the err field — pino serializes Error objects correctly
try { await processOrder(); }
catch (err) { requestLogger.error({ err }, 'Order processing failed'); }

Why

JSON logs are trivially queryable by log aggregation systems (Loki, Elasticsearch, Datadog). Adding a field to every log line in a request context is O(1) with child loggers — no global state needed.

Gotchas

  • Never log sensitive data — sanitize PII, tokens, and passwords before logging
  • pino is 5-10x faster than winston because it avoids synchronous formatting — important under high load
  • The err field must be named 'err' (not 'error') for pino's built-in error serializer to work
  • In production, never use pino-pretty — it is 10x slower than raw JSON output

Context

Setting up production-grade logging in a Node.js service

Revisions (0)

No revisions yet.