node.js - prom-client 在 NodeJS 应用程序中返回默认指标的空对象

标签 node.js npm prometheus

我有一个 NodeJS 应用程序,我想公开默认指标。我有以下实现。我正在使用prom-client包。

let express = require('express');
let app = express();

const client = require('prom-client');

// Create a Registry which registers the metrics
const register = new client.Registry()

// Add a default label which is added to all metrics
register.setDefaultLabels({
    app: 'example-nodejs-app'
})

// Enable the collection of default metrics
client.collectDefaultMetrics({ register })

app.get('/metrics', function (req, res) {
    // Return all metrics the Prometheus exposition format
    res.set('Content-Type', register.contentType)
    res.send(register.metrics())
})

let server = app.listen(8080, function () {
    let port = server.address().port
    console.log("Application running on port: %s", port)
})

当我导航到 http://localhost:8080/metrics 时,我得到一个空对象 ({}) 作为响应。当我检查我的 Prometheus 目标时,我看到以下错误。

"INVALID" is not a valid start token

enter image description here

我最近使用 npm 的舞会客户端。我怎样才能做到这一点?

最佳答案

发现问题了。您需要意识到的是,register.metrics() 返回一个 promise 。因此,使用 await register.metrics() 将返回默认指标的预期响应。更新后的代码片段如下。

let express = require('express');
let app = express();

const client = require('prom-client');

// Create a Registry which registers the metrics
const register = new client.Registry()

// Add a default label which is added to all metrics
register.setDefaultLabels({
    app: 'example-nodejs-app'
})

// Enable the collection of default metrics
client.collectDefaultMetrics({ register })

app.get('/metrics', async function (req, res) {
    // Return all metrics the Prometheus exposition format
    res.set('Content-Type', register.contentType);
    let metrics = await register.metrics();
    res.send(metrics);
})

let server = app.listen(8080, function () {
    let port = server.address().port
    console.log("Application running on port: %s", port)
})

现在,导航至 http://localhost:8080/metrics在浏览器中查看默认指标。

关于node.js - prom-client 在 NodeJS 应用程序中返回默认指标的空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68160376/

相关文章:

javascript - 为什么 setTimeout(0) 和 setImmediate() 的行为在主模块中使用时未定义?

Prometheus服务器自动重新加载规则

grafana - 如何在grafana图例中添加自定义值?

node.js - AWS JS SDK 不从环境变量加载凭证

java - 关于框架(概念)

node.js - NodeJS npm - 在 Windows 上使用 Contextify

windows - windows 7下安装yuidoc

angular - Karma 测试参数 --watch=false 不起作用

linux - Prometheus 2.0 centos 服务无法启动,因为 "Opening storage failed", "permission denied"

node.js - nginx 配置 - 将 http 转发到 https,将 www.domain.tld 转发到 domain.tld 和两个子域