Node.js Logging Guide
Here’s a complete and practical guide on Node.js Logging — covering why logging is important, built-in methods, logging libraries, structured logging, and best practices.
📝 Node.js Logging Guide
Logging is essential for:
Debugging errors
Monitoring production apps
Auditing and compliance
Performance analysis
Node.js provides built-in logging with console, but for production-grade apps, specialized logging libraries are recommended.
1️⃣ Basic Logging with console
Node.js provides simple logging functions:
Example:
❌ Limitation:
consolelogs are unstructured and not persistent.
2️⃣ File Logging with fs
You can write logs to a file using the Node.js fs module:
❌ Limitation: Manual file rotation and log levels need to be implemented manually.
3️⃣ Using Logging Libraries
For production apps, use logging libraries like:
3.1 Winston (Most Popular)
Example:
✅ Features:
Multiple transports (console, file, HTTP)
Log levels (error, warn, info, debug)
JSON formatting for structured logs
3.2 Morgan (HTTP Request Logging for Express)
Example:
✅ Features:
Pre-defined log formats:
combined,common,devCan log to a file using
fs.createWriteStream
3.3 Pino (High-performance JSON Logger)
Example:
✅ Features:
Extremely fast
Structured JSON logging
Works well with log aggregators
4️⃣ Log Levels
Common log levels:
| Level | Description |
|---|---|
| error | Critical issues, app crashes |
| warn | Warnings, non-critical errors |
| info | General information |
| http | HTTP request info |
| verbose | Detailed info for debugging |
| debug | Developer-focused debug info |
| silly | Most granular debug info |
Libraries like Winston and Pino support multiple levels.
5️⃣ Structured Logging
Instead of plain text, structured logs (JSON) help with:
Searching logs in ELK (Elasticsearch, Logstash, Kibana)
Aggregation & monitoring
Debugging in production
6️⃣ Log Rotation
Prevent log files from growing indefinitely:
7️⃣ Logging Best Practices
Use levels (
error,warn,info,debug)Do not log sensitive data (passwords, tokens)
Use structured logging (JSON) for production
Log HTTP requests (Morgan or Pino HTTP)
Use log rotation to avoid huge files
Centralize logs with ELK, Grafana Loki, or CloudWatch
Separate dev & prod logging
8️⃣ Example: Production-ready Logger
Use in your app:
🎯 Summary
consoleis enough for small appsUse Winston, Pino, or Morgan for production apps
Structured logs (JSON) help with monitoring and debugging
Use log levels, rotation, and avoid sensitive data
Integrate with ELK Stack, CloudWatch, or Grafana for central monitoring
