Monitoring and Health Checks
Monitor Node.js apps. Learn metrics and alerts.
Monitoring and Health Checks
Health Check Endpoint
```javascript app.get('/health', async (req, res) => { const health = { uptime: process.uptime(), timestamp: Date.now(), status: 'ok' }; try { await mongoose.connection.db.admin().ping(); health.database = 'connected'; await redisClient.ping(); health.redis = 'connected'; res.json(health); } catch (error) { health.status = 'error'; health.error = error.message; res.status(503).json(health); } }); ```
Track Response Time
```javascript app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; console.log(`${req.method} ${req.url} - ${duration}ms`); if (duration > 1000) { console.warn('Slow request detected'); } }); next(); }); ```
Key Takeaway
Implement health checks. Track response times. Alert on anomalies. Use monitoring services.