nodejs-prometheus-metrics

Prom-client wrapper for nodejs services

Usage no npm install needed!

<script type="module">
  import nodejsPrometheusMetrics from 'https://cdn.skypack.dev/nodejs-prometheus-metrics';
</script>

README

Metrics Controller for NodeJS based APIs

This is a simplified wrapper in hopes of standardizing the metrics reported for our NodeJS based services to Prometheus

Kuberentes Config

Annotate the Service Defintion

Assuming the api/service base path is at: /api

apiVersion: v1
kind: Service
metadata:
  name: example-api
  labels:
    app: example
    environment: dev
    tier: api
  annotations:
    prometheus.io/path: "/api/metrics"
    prometheus.io/scrape: "true"

NOTE: If your api does not have a base path and the metrics will be available at /metrics then you can eliminate the prometheus.io/path annotation

This is the best documentation (at time of writing): Prometheus Config Docs

swagger.yaml Config

  /metrics:
    x-swagger-router-controller: metrics
    get:
      description: Returns api metrics for Prometheus
      operationId: getMetrics
      produces:
       - text/plain
      responses:
        "200":
          description: success
          schema:
            type: string

API Setup

Default Metrics

Default metrics will be collected unless you set the autoStart option to false. Default metrics come from prom-client library

Per Request Metrics

Inorder to collect per-request metrics, you must add the middleware to your app / server. The RPM class exposes this via the requestMiddleware method.

Example Setup

app.js

const restify = require('restify');
const Metrics = require('nodejs-prometheus-metrics');
const app = restify.createServer();

const metrics = new Metrics({
  prefix: 'my_cool_api_',
  requestObjPath: 'swagger.apiPath'
});

app.use(metrics.requestMiddleware);

metricsController.js

const Metrics = require('nodejs-prometheus-metrics');
const metrics = new Metrics();

function requestController(req, res, next) {
    metrics.getMetrics();
    return next();
}

module.exports = requestController

Options

Name (type) Default Description
autoStart (bool) true Start Collection default metrics. If you set this value to false you must call start to collect default metricss
requestObjPath (string / function) 'path' Path in the request object that should be used for determining the path of the request. ex. With swagger it obfuscates the path request therefore swagger.apiPath can be used
metricsEndpoint (string) '/metrics' if your api uses a different path for metrics. ex. /api/metrics
promTimeout (int) 5000 Time in MS between metric collections