Chapter 14: Monitoring and Debugging
Chapter 14 of 15
Chapter 14: Monitoring and Debugging
14.1 Application Monitoring
Monitoring helps track application health, performance, and errors in production.
// PM2 monitoring
// npm install -g pm2
// pm2 start app.js
// pm2 monit
// pm2 logs
// Application metrics
const prometheus = require('prom-client');
const httpRequestDuration = new prometheus.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code']
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000;
httpRequestDuration.observe({
method: req.method,
route: req.route?.path || req.path,
status_code: res.statusCode
}, duration);
});
next();
});
14.2 Health Checks
// Health check endpoint
app.get('/health', async (req, res) => {
const health = {
uptime: process.uptime(),
message: 'OK',
timestamp: Date.now(),
database: await checkDatabase(),
redis: await checkRedis()
};
const statusCode = health.database && health.redis ? 200 : 503;
res.status(statusCode).json(health);
});
14.3 Error Tracking
// Sentry integration
const Sentry = require('@sentry/node');
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV
});
// Capture exceptions
try {
riskyOperation();
} catch (error) {
Sentry.captureException(error);
}
14.4 Debugging
// Node.js inspector
// node --inspect app.js
// Open chrome://inspect
// Debug logging
const debug = require('debug')('app:server');
debug('Server starting on port %d', port);
// Enable: DEBUG=app:* node app.js