Prometheus on API endpoint and Grafana

Hello,

I am new with Grafana and Prometheus.

I want to manage metrics on my API in order to expose it on Grafana. I created a new endpoint for that with a basic authentication. It is working fine on Postman and on web browser.

Now my question is how can I connect my API metrics/endpoint with Grafana ?

Because I have an error (invisible) when I try to create new data source in Grafana.

If you want, you can find attached, a screenshot of the error and my JS file.

Thanks.

'use strict';

/**
 * PACKAGES
 */
const Register = require('prom-client').register;
const Counter = require('prom-client').Counter;
const Histogram = require('prom-client').Histogram;
const Summary = require('prom-client').Summary;
const ResponseTime = require('response-time');

/**
 * VARIABLES
 */
const numOfRequests = new Counter({
    name: 'numOfRequests',
    help: 'Number of requests made',
    labelNames: ['method']
});

const pathsTaken = new Counter({
    name: 'pathsTaken',
    help: 'Paths taken in the app',
    labelNames: ['path']
});

const responses =  new Summary({
    name: 'response',
    help: 'Response time in millis',
    labelNames: ['method', 'path', 'status']
});

module.exports.startCollection = function () {
    require('prom-client').collectDefaultMetrics({
        remote_write: { url: ''}
    });
};

module.exports.requestCounters = function (req, res, next) {
    if (req.path !== '/metrics') {
        numOfRequests.inc({ method: req.method });
        pathsTaken.inc({ path: req.path });
    }
    next();
};

module.exports.responseCounters = ResponseTime(function(req, res, time) {
    if (req.path !== '/metrics') {
        responses.labels(req.method, req.url, res.statusCode).observe(time);
    }
    res.setHeader('X-Response-Time', time);
});

module.exports.injectMetricsRoute = function (app) {
    app.get('/metrics', (req, res) => {
        res.set('Content-Type', Register.contentType);
        res.end(Register.metrics());
    });
};

Hi nyhillius,

It looks like you’re trying to get Grafana to consume your prometheus compatible metrics endpoint directly from Grafana. That’s unfortunately not how Grafana and Prometheus works together. You will have to setup a Prometheus server and configure it to scrape metrics from the metrics endpoint you have created. When you have done that you can create a Datasource in Grafana for your Prometheus server. (Basically Grafana -> Prometheus -> Your endpoint)

The Prometheus project’s Getting Started documentation would probably be a good place to start. https://prometheus.io/docs/prometheus/latest/getting_started/

Good luck!

Thank you. My bad. It became clear now “Prometheus collects metrics from monitored targets by scraping metrics HTTP endpoints on these targets”. I will try. Thank you very much.

1 Like