Your production logs are a wall of unstructured text. Grep fails. Debugging takes hours. You need structured logging.
The Problem
User login failed for john@example.com
Error processing payment
Connection timeout after 30s
Which user? Which payment? Which service timed out? Unstructured logs cannot answer these questions.
Structured Logging with Pino
import pino from "pino";
const logger = pino({ level: process.env.LOG_LEVEL || "info" });
// Instead of: console.log("User login failed for " + email)
// Do: logger.warn({ userId, email, reason }, "Login failed")
Output: {"level":40,"time":"2026-03-21T...","userId":"u_123","email":"john@example.com","reason":"invalid_password","msg":"Login failed"}
Request Context Middleware
Every log in a request should include requestId, method, path, userId:
app.use((req, res, next) => {
req.log = logger.child({ requestId: crypto.randomUUID(), method: req.method, path: req.path });
next();
});
Now every log in that request automatically includes the requestId. Trace a single request across your entire system.
Log Levels Done Right
error = broken, warn = recoverable, info = business events, debug = dev context
Sensitive Data Redaction
Never log passwords, tokens, credit card numbers, or PII. Use pino redact:
const logger = pino({ redact: ["password", "token", "req.headers.authorization"] });
Shipping Logs
JSON logs pipe directly to Datadog, Elasticsearch, CloudWatch, Grafana Loki. No parsing regex needed.
Summary
- Use Pino (fastest Node.js logger)
- Log JSON, not strings
- Add requestId to every log via child loggers
- Use correct log levels
- Redact sensitive data
- Ship to centralized logging
Part of my Production Backend Patterns series. Follow for more practical backend engineering.
If this was useful, consider:
- Sponsoring on GitHub to support more open-source tools
- Buying me a coffee on Ko-fi
You Might Also Like
- Environment Variables Done Right: From .env Files to Production Configs
- Docker Compose for Development: The Setup Every Backend Dev Needs
- Database Migrations in Production: Zero-Downtime Schema Changes (2026 Guide)
Follow me for more production-ready backend content!
If this helped you, buy me a coffee on Ko-fi!
Top comments (0)