ubuntu

如何在Ubuntu上监控Node.js应用性能

小樊
36
2025-08-05 16:06:53
栏目: 编程语言

在Ubuntu上监控Node.js应用性能有多种方法,以下是一些常用的工具和方法:

使用PM2进行进程管理

使用systemd服务

[Unit]
Description=My Node.js Application
After=network.target

[Service]
ExecStart=/usr/bin/node /path/to/your/app.js
Restart=always
User=your-user
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

使用Prometheus和Grafana进行监控

const client = require('prom-client');
const requestDuration = new client.histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of http requests in seconds',
  labelnames: ['method', 'status']
});
const activeRequests = new client.gauge({
  name: 'active_requests',
  help: 'Number of active requests'
});

app.use((req, res, next) => {
  const end = requestDuration.startTimer();
  activeRequests.inc();
  res.on('finish', () => {
    end({ method: req.method, status: res.statusCode });
    activeRequests.dec();
  });
  next();
});

app.get('/metrics', async (req, res) => {
  res.set('content-type', client.register.contentType);
  res.send(await client.register.metrics());
});

使用Winston进行日志记录

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');

使用node-statsd进行性能监控

通过上述方法,您可以在Ubuntu系统上有效地监控Node.js应用的性能和资源使用情况,确保应用的稳定性和高可用性。

0
看了该问题的人还看了