🎓 A1Learner
🔍
0 of 50 lessons completed

Prometheus: Expose Metrics from Your Own Code

A client library is a small package that adds metrics to your own code. It counts, times, and publishes the numbers for Prometheus.

Install the Python client

One install command adds the client library to the machine.

pip3 install --user --break-system-packages prometheus_client

Count requests by route

One line creates the counter, and one line adds one to it.

REQUESTS = Counter("demo_requests_total", "Requests served", ["route"])
REQUESTS.labels(route="/").inc()

Time requests with a histogram

One line creates the histogram, and one line records a time of 0.042 seconds.

LATENCY = Histogram("demo_request_seconds", "Request latency", ["route"])
LATENCY.labels(route="/").observe(0.042)

Example

from prometheus_client import Counter, Histogram, start_http_server
REQUESTS = Counter("demo_requests_total", "Requests served", ["route"])
LATENCY = Histogram("demo_request_seconds", "Request latency", ["route"])
REQUESTS.labels(route="/").inc()
LATENCY.labels(route="/").observe(0.042)
start_http_server(18113)

Key points

  • A client library is a package you import, so your code can record metrics.
  • A counter in code counts each request as it arrives, labelled by route.
  • A histogram in code times each request and sorts it into buckets.
  • The library serves the numbers on a /metrics page, just like ShopSentry does.
  • Six short lines add a request counter, a latency histogram, and the metrics page.
  • The Python client is called prometheus_client, and version 0.26.0 was used here.

In this example, six lines of real Python expose real metrics on port 18113. The counter reads 1.0 after one request, and the histogram holds one observation of 0.042 seconds. The same six lines add metrics to any small service.

Note

Go and Java have client libraries with the same idea, so the pattern travels across languages.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does start_http_server do in the client library example?