监控 Ubuntu 上的 Node.js 应用
一 监控分层与总体方案
二 快速上手 PM2 与 systemd
[Unit]
Description=Node.js Application
After=network.target
[Service]
Type=simple
User=<your-user>
WorkingDirectory=/path/to/your/app
ExecStart=/usr/bin/node /path/to/your/app/app.js
Restart=always
[Install]
WantedBy=multi-user.target
三 日志监控与最佳实践
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('Application started');
logger.error('An error occurred:', error);
四 指标与可视化 告警
const client = require('prom-client');
const httpRequestDuration = new client.Histogram({
name: 'http_request_duration_ms',
help: 'Duration of HTTP requests in ms',
labelNames: ['method', 'route', 'code'],
buckets: [0.1, 5, 15, 50, 100, 200, 300, 400, 500]
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
httpRequestDuration
.labels(req.method, req.route || req.path, res.statusCode)
.observe(Date.now() - start);
});
next();
});
五 进阶排障与性能分析
const heapdump = require('heapdump');
heapdump.writeSnapshot('/path/to/snapshot.heapsnapshot');