Structured Logging in Node.js With Pino
console.log('error!', err) is fine on your laptop. In production with ten instances and millions of requests, you need structured logs — JSON with consistent fields you can filter and chart.
Why Pino
Pino is a fast, low-overhead JSON logger widely used in Node.js (and built into Fastify).
import pino from 'pino';
export const logger = pino({
level: process.env.LOG_LEVEL || 'info',
redact: ['req.headers.authorization', 'password', 'card.number'],
});
logger.info({ orderId: 'o-123', amount: 499 }, 'order created');
Output:
{"level":30,"time":1763600000000,"orderId":"o-123","amount":499,"msg":"order created"}
Log Levels
fatal/error— something failedwarn— unexpected but handledinfo— important business eventsdebug— detail for troubleshooting (off in production by default)
Request Context
Use child loggers so every log line includes a request ID:
app.use((req, res, next) => {
req.log = logger.child({ requestId: req.headers['x-request-id'] || crypto.randomUUID() });
next();
});
pino-http does this automatically for Express.
Redaction
Never log passwords, tokens, full card numbers, or unnecessary personal data. Use redact paths.
Pretty Logs in Development
node server.js | npx pino-pretty
Shipping Logs
Log to stdout; let your platform or agent forward logs to New Relic, Elastic, Datadog, or a cloud logging service. Include trace IDs to connect logs with traces.
Log events, not essays. Structured fields turn logs into data.