Chapter 3. Instrumentation

The largest payoffs you will get from Prometheus are through instrumenting your own applications using direct instrumentation and a client library. Client libraries are available in a variety of languages, with official client libraries in Go, Python, Java, Rust, and Ruby.

We use Python 3 here as an example, but the same general principles apply to other languages and runtimes, although the syntax and utility methods will vary.

Most modern OSes come with Python 3. In the unlikely event that you don’t already have it, download and install Python 3.

You will also need to install the latest Python client library. You can do this with pip install prometheus_client. You can find the instrumentation examples on GitHub.

A Simple Program

To start things off, we have written a simple HTTP server shown in Example 3-1. If you run it with Python 3 and then visit http://localhost:8001/ in your browser, you will get a Hello World response.

Example 3-1. A simple Hello World program that also exposes Prometheus metrics
import http.server
from prometheus_client import start_http_server

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Hello World")

if __name__ == "__main__":
    start_http_server(8000)
    server = http.server.HTTPServer(('localhost', 8001), MyHandler)
    server.serve_forever()

The start_http_server(8000) starts up an HTTP server on port 8000 to serve metrics to Prometheus. You ...

Get Prometheus: Up & Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.