Node.js中的Prometheus客户端-设置标签值

时间:2018-10-17 11:58:45

标签: node.js prometheus

我在Prometheus上使用prom-client。 我像这样初始化直方图,现在处理完请求后,我想设置处理它的时间(我是从节点请求对象获得的)并设置标签值。

const southboundMetricsHistogram = prometheusClient.register.getSingleMetric(consts.PROMETHEUS_SOUTHBOUND_METRICS_NAME) ||
    new prometheusClient.Histogram({
        name: consts.PROMETHEUS_SOUTHBOUND_METRICS_NAME,
        help: consts.PROMETHEUS_SOUTHBOUND_METRICS_DESC,
        labelNames: ['target', 'route', 'status_code', 'method'],
        buckets: consts.PROMETHEUS_SOUTHBOUND_DURATION_SIZES_BUCKETS
    });

我尝试使用observelabels,但出现错误。 可以设置经过时间和标签值吗?

谢谢。

3 个答案:

答案 0 :(得分:0)

为此,似乎node.js客户端库中的直方图具有内置的startTimer()函数。

在其Github上的“示例”部分下,给出了以下示例:

const end = histogram.startTimer();
xhrRequest(function(err, res) {
end(); // Observes the value to xhrRequests duration in seconds
});

因此,您可以仅在发出请求时启动计时器,然后在发送响应时停止计时器。

Source

答案 1 :(得分:0)

像这样解决:

southboundMetricsHistogram.observe({target: request.target, method: request.method, route: response.req.path, status_code: response.statusCode}, response.elapsedTime);

答案 2 :(得分:0)

这是一个完整的例子

    import express from 'express';
    import pino from 'pino';
    import expressPino from 'express-pino-logger';
    import promClient from 'prom-client';
    
    const PORT = process.env.PORT || 5555;
    
    const logger = pino({level:process.env.LOG_LEVEL || 'info'})
    const expressLogger = expressPino({logger});
    
    const app = express();
    app.use(express.json(), expressLogger);
    
    // Create a Registry which registers the metrics
    const register = new promClient.Registry()
    promClient.collectDefaultMetrics({ register });
    
    const Histogram = promClient.Histogram;
    const requestDuration = new Histogram({
        name: 'http_request_duration_seconds',
        help: 'request duration histogram',
        labelNames: ['handler' , 'method', 'statuscode'],
        //buckets: [0.5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
        buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
    });
    
    // Register the histogram
    register.registerMetric(requestDuration)
    
    const profilerMiddleware = (req, res, next) => {
        //const start = Date.now();
        const end = requestDuration.startTimer()
        res.once('finish', () => {
        //const duration = Date.now() - start;
        //requestDuration.labels(req.url, req.method, res.statusCode).observe(duration);
        //requestDuration.observe({ handler:req.url, method: req.method, statuscode: res.statusCode }, duration);
        const duration = end({ handler:req.url, method: req.method, statuscode: res.statusCode });
        logger.info('Duration  %d', duration);
        });
    
    next();
    };
    app.use(profilerMiddleware);
    
    
    app.get('/health', (req, res) => {
        logger.debug('Calling res.send');    
        return res.status(200).send({message: "Health is good"});
    });
    
    app.listen(PORT, () => {
        logger.info('App is listening for requests on port %d', PORT);
    });
    
    // Setup server to Prometheus scrapes:
    app.get('/metrics', async (req, res) => {
        try {
            res.set('Content-Type', register.contentType);
            res.end(await register.metrics());
        } catch (ex) {
            res.status(500).end(ex);
        }
    });