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, and Ruby.

I 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 from https://www.python.org/downloads/.

You will also need to install the latest Python client library. This can be done with pip install prometheus_client. The instrumentation examples can be found on GitHub.

A Simple Program

To start things off, I 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 a HTTP server on port 8000 ...

Get Prometheus: Up & Running 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.