Structured Logging Best Practices: Node.js
Structured logging makes production debugging possible. Here's how to do it right in Node.js.
What this problem means
Unstructured logs—plain text, inconsistent format—are hard to search and trace. Structured logging uses JSON with consistent fields (request_id, user_id, error, timestamp). It makes logs searchable and traceable across services.
Why this is dangerous
- Debugging blind: Without structured logs, you can't trace a request across services.
- Extended outages: Finding the cause of a failure takes hours instead of minutes.
- No correlation: Plain text logs don't correlate with metrics or traces.
Real-world example
A startup had plain text logs: "Error occurred." When a user reported a failure, they had no way to trace the request. They spent two days reproducing the issue. With structured logs and request_id, they could have found it in minutes.
How to fix it
1. Use JSON: Log as JSON with `request_id`, `user_id`, `error`, `message`, `timestamp`.
2. Request IDs: Generate a unique ID per request. Pass it through all services.
3. Log levels: Use ERROR, WARN, INFO. Avoid DEBUG in production.
4. No sensitive data: Never log passwords, tokens, or PII.
5. Centralized: Send logs to CloudWatch, Datadog, or similar.
Tools and configurations
- Pino: Fast JSON logger for Node.js. Low overhead.
- Winston: Flexible logger with transports.
- express-request-id: Middleware to add request_id.
- CloudWatch / Datadog: Centralized log storage and search.
Common mistakes
- Plain text logs instead of JSON.
- No request_id for tracing.
- Logging sensitive data.
- No centralized log storage.
Quick checklist
- [ ] Use JSON logger (Pino or Winston)
- [ ] Add request_id to every log
- [ ] Set log levels (ERROR, WARN, INFO)
- [ ] Never log passwords, tokens, or PII
- [ ] Send logs to CloudWatch or similar
Need help with production readiness? Get a free 30-minute audit.
Book Free 30-Min Production AuditCheck if your system has this risk
Take the 60-second production readiness assessment to identify gaps in your infrastructure.
Start AssessmentFrequently asked questions
- What is structured logging in Node.js?
- Structured logging uses JSON with consistent fields (request_id, user_id, error, timestamp). It makes logs searchable and traceable. Use Pino or Winston for Node.js.
- What should I log in production?
- Log request_id, user_id (if applicable), error, message, and timestamp. Never log passwords, tokens, or PII. Use log levels: ERROR, WARN, INFO.
- How do I add request_id to Node.js logs?
- Use express-request-id or similar middleware to generate a unique ID per request. Pass it through all services and include it in every log entry.