Skip to content

Instantly share code, notes, and snippets.

@nicosingh
Last active October 18, 2018 14:02
Show Gist options
  • Save nicosingh/391e215609b5c3b5f83daf7356bedd77 to your computer and use it in GitHub Desktop.
Save nicosingh/391e215609b5c3b5f83daf7356bedd77 to your computer and use it in GitHub Desktop.
Custom prometheus metrics 101

Custom prometheus metrics 101

Contents:

Types of metrics

  • Counter
  • Gauge
  • Histogram
  • Summary

Taken from: https://prometheus.io/docs/concepts/metric_types/

Python sample

Prepare (or go) to your application folder:

virtualenv my-coolest-app-python
cd my-coolest-app-python
source bin/activate

Install dependencies:

pip install prometheus_client

Create your metrics exporter:

# metrics.py

from prometheus_client import start_http_server, Gauge
import time

# define my custom metric
req_num = Gauge('req_num', 'Just a random gauge')

# calculate metric value
def process_request():
    req_num.set(42)

if __name__ == '__main__':
    # expose metrics in a web server
    start_http_server(8000)
    # generate metrics forever
    while True:
        process_request()

Run it:

python metrics.py

Your metrics will be available at http://localhost:8000/metrics

Reference: https://github.com/prometheus/client_python

NodeJS sample

Prepare (or go) to your application folder:

mkdir -p my-coolest-app-node
cd my-coolest-app-node

Install dependencies:

npm install prom-client express

Create your metrics exporter:

// metrics.js

const Prometheus = require('prom-client')
const server = require('express')()

const PrometheusMetrics = {
  // define my custom metric
  reqNum: new Prometheus.Gauge('req_num', 'Just a random gauge')
}

server.use((req, res, next) => {
  // calculate metric value
  PrometheusMetrics.reqNum.set(42)
  next()
})

server.get('/metrics', (req, res) => {
  // register metrics
  res.end(Prometheus.register.metrics())
})

// expose metrics in a web server
server.listen(3000)

Run it:

node metrics.js

Your metrics will be available at http://localhost:3000/metrics

Reference: https://github.com/siimon/prom-client

What should I monitor?

  • number of requests
  • endpoint healthchecks
  • endpoint response time
  • ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment