在Ubuntu系统中监控Node.js应用程序有多种方法,以下是一些常用的工具和方法:
PM2是一个流行的Node.js进程管理器,它可以帮助你监控和管理Node.js应用。
sudo npm install pm2 -g
pm2 start app.js --name "my-app"
pm2 monit
使用 pm2 monit
命令可以查看应用的实时状态、CPU和内存使用情况。
Ubuntu自带了一个名为“系统监视器”的图形界面工具,可以用来监控系统资源使用情况,包括Node.js应用程序。
htop是一个交互式的进程查看器,可以用来监控系统资源使用情况和查找特定进程。
sudo apt install htop
htop
在htop中,你可以看到所有正在运行的进程,并可以根据CPU、内存等资源使用情况进行筛选和排序。
Node.js提供了一些内置的性能监控工具,如 process.memoryUsage()
和 process.cpuUsage()
,可以用来获取应用的内存和CPU使用情况。
const memoryUsage = process.memoryUsage();
console.log(memoryUsage);
const cpuUsage = process.cpuUsage();
console.log(cpuUsage);
Prometheus是一个强大的开源监控系统和时间序列数据库,可以与Grafana结合使用,提供强大的可视化功能。
npm install prom-client
const client = require('prom-client');
const httpRequestDurationMicroseconds = new client.Histogram({
name: 'http_request_duration_ms',
help: 'Duration of HTTP requests in ms',
labelNames: ['method', 'route', 'code'],
buckets: [0.10, 5, 15, 50, 100, 200, 300, 400, 500]
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
httpRequestDurationMicroseconds
.labels(req.method, req.route, res.statusCode)
.observe(duration);
});
next();
});
app.get('/metrics', async (req, res) => {
res.set('content-type', client.register.contentType);
res.send(await client.register.metrics());
});
New Relic是一个全栈的应用性能管理(APM)工具,可以监控Node.js应用的性能、错误和日志。
Datadog是一个云原生监控平台,支持Node.js应用程序的监控和分析,提供实时监控、日志管理等功能。
通过上述方法,你可以在Ubuntu上有效地监控Node.js应用的性能和资源使用情况,确保应用的稳定运行。