Monitoring and logging are essential for production applications to detect errors, track performance, and ensure reliability.
🔹 1. Logging
Purpose: Track events, errors, and important actions in your app.
Common Tools:
- Winston – flexible logging library with multiple transports (console, file, remote).
- Morgan – HTTP request logging for Express.js.
- Bunyan – JSON-based structured logging for easy parsing.
Example with Winston:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
logger.info('Server started');
logger.error('Something went wrong');
Example with Morgan in Express:
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('combined')); // Logs HTTP requests
🔹 2. Monitoring
Purpose: Observe app health, performance, and resource usage.
Approaches:
- Application Performance Monitoring (APM):
- Tools: New Relic, Datadog, AppDynamics, Elastic APM
- Monitor response times, throughput, error rates, CPU/memory usage.
- Process Monitoring:
- Tools: PM2, Forever
- Keep Node.js processes alive, monitor CPU/memory, enable automatic restarts.
# Start app with PM2 and enable monitoring
pm2 start server.js --name my-app
pm2 monit
- Custom Metrics:
- Use libraries like prom-client for Prometheus metrics: request counts, response times, memory usage.
- Expose metrics endpoint and integrate with Grafana for visualization.
🔹 3. Error Tracking
- Capture unhandled errors and rejections:
process.on('uncaughtException', (err) => {
logger.error('Uncaught Exception:', err);
});
process.on('unhandledRejection', (reason) => {
logger.error('Unhandled Rejection:', reason);
});
- Integrate with Sentry or LogRocket for real-time error tracking.
🔹 4. Key Best Practices
- Log structured JSON for easier parsing and aggregation.
- Separate error logs and info logs.
- Rotate logs to avoid disk full issues (
winston-daily-rotate-file). - Monitor CPU, memory, response times, DB latency, and API errors.
- Set up alerts for critical thresholds.
✅ Summary:
- Use Winston/Morgan for logging, PM2/APM tools for monitoring.
- Capture uncaught exceptions and unhandled promise rejections.
- Visualize metrics and set up alerts to maintain production health.