5 min read
ā¢Question 28 of 28hardHow do you monitor APIs in production?
API monitoring and observability.
What You'll Learn
- Key metrics to monitor
- Logging strategies
- Monitoring tools
Key Metrics
- Latency - Response time (p50, p95, p99)
- Traffic - Requests per second
- Errors - Error rate percentage
- Saturation - Resource utilization
Logging
code.jsJavaScript
const morgan = require('morgan');
const winston = require('winston');
// Request logging
app.use(morgan(':method :url :status :response-time ms'));
// Structured logging
const logger = winston.createLogger({
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
// Log API calls
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
logger.info({
method: req.method,
url: req.url,
status: res.statusCode,
duration: Date.now() - start,
userAgent: req.get('user-agent'),
});
});
next();
});Health Check Endpoint
code.jsJavaScript
app.get('/health', async (req, res) => {
const health = {
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
checks: {
database: await checkDatabase(),
redis: await checkRedis(),
},
};
const isHealthy = Object.values(health.checks).every(c => c.status === 'ok');
res.status(isHealthy ? 200 : 503).json(health);
});Monitoring Tools
- Datadog - Full observability
- New Relic - APM
- Prometheus + Grafana - Open source
- Sentry - Error tracking
- ELK Stack - Log management