在 Ubuntu 上监控 Node.js 应用可以通过多种工具和方法实现,以下是一些常用的方法和工具:
安装 Node.js 的 Prometheus 客户端:
npm install prom-client
设置 Prometheus 指标: 在 Node.js 应用程序中定义请求持续时间、活动请求等指标:
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();
});
公开指标端点: 创建端点以向 Prometheus 公开指标:
app.get('/metrics', async (req, res) => {
res.set('content-type', client.register.contentType);
res.send(await client.register.metrics());
});
使用 Grafana 进行可视化: 将 Prometheus 连接到 Grafana 并创建自定义仪表板以可视化请求率、延迟和内存使用等指标。
安装 Winston:
npm install winston
配置 Winston:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.console(),
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');
安装 Tinymonit:
npm install tinymonit -g
收集系统监控信息:
const tm = require('tinymonit');
const osstat = tm.osstat;
Promise.resolve().then(() => osstat([8122])).then((stat) => console.log(stat));
app.get('/health', (req, res) => {
const healthstatus = { uptime: process.uptime(), message: 'ok', timestamp: Date.now() };
res.status(200).send(healthstatus);
});
通过上述方法,您可以在 Ubuntu 上有效地监控 Node.js 应用的性能和健康状况。结合使用 Prometheus、Grafana、Winston 和 Tinymonit 等工具,您可以获得全面的监控数据,从而更好地理解和优化您的应用。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: ubuntu系统如何查看内存