Node.js 中的 Prometheus 指标:用于监控的 prom-client 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

prom-client 库:使用 Prometheus 监控 Node.js 应用



在现代 Web 开发中,监控应用程序的性能和状态已成为一项必要任务。最流行的指标收集和分析解决方案之一是 Prometheus——一个以时间序列形式收集数据的开源系统。为了与 Node.js 集成,官方提供了 prom-client 库,它能够轻松地以 Prometheus 可理解的格式导出指标。



在本文中,我们将详细介绍如何安装和使用 prom-client,有哪些可用的指标类型,以及如何将它们与 Web 框架 Express 集成。



安装与引入



首先,通过 npm 安装该库:



npm install prom-client


安装后,将其导入到您的应用程序中:



const prometheus = require('prom-client');const express = require('express');const app = express();


主要指标类型



prom-client 库支持四种主要的 Prometheus 指标类型:



  • Counter —— 只增不减的计数器(例如,请求总数)。
  • Gauge —— 可增可减的值(例如,活跃连接数)。
  • Histogram —— 测量值分布的直方图(例如,响应时间)。
  • Summary —— 类似于 Histogram 的汇总统计,但具有更精确的分位数。


示例:Counter(请求计数器)



创建一个计数器来跟踪 HTTP 请求的总数:



const httpRequestsTotal = new prometheus.Counter({  name: 'http_requests_total',  help: 'Total number of HTTP requests',  labelNames: ['method', 'route', 'status']});

// 用于计数请求的中间件app.use((req, res, next) => { res.on('finish', () => { httpRequestsTotal.inc({ method: req.method, route: req.path, status: res.statusCode }); }); next();});


示例:Gauge(活跃连接数)



Gauge 适用于跟踪当前状态,例如活跃用户数:



const activeUsers = new prometheus.Gauge({  name: 'active_users',  help: 'Number of active users'});

app.get('/login', (req, res) => { activeUsers.inc(); // 登录时增加 res.send('Logged in');});

app.get('/logout', (req, res) => { activeUsers.dec(); // 退出时减少 res.send('Logged out');});


示例:Histogram(响应时间)



Histogram 可以测量处理请求所需的时间:



const httpRequestDuration = new prometheus.Histogram({  name: 'http_request_duration_seconds',  help: 'Duration of HTTP requests in seconds',  labelNames: ['method', 'route'],  buckets: [0.1, 0.5, 1, 2, 5] // 以秒为单位的桶边界});

app.use((req, res, next) => { const end = httpRequestDuration.startTimer(); res.on('finish', () => { end({ method: req.method, route: req.path }); }); next();});


为 Prometheus 导出指标



为了让 Prometheus 能够收集数据,需要创建一个端点(通常是 /metrics),该端点返回所有已注册的指标:



app.get('/metrics', async (req, res) => {  res.set('Content-Type', prometheus.register.contentType);  res.end(await prometheus.register.metrics());});

app.listen(3000, () => { console.log('Server running on port 3000');});


带标签的自定义指标



您可以添加标签(labels)以实现更详细的过滤。例如,按 API 版本划分指标:



const apiCalls = new prometheus.Counter({                    

推荐