writing a simple prometheus exporter to collect metrics from a external system that needs monitoring. I will use the python official prometheus_client package for python and falcon to serve the exporter.
notise the following example is written with the assumtion that you are collection metrics from some other systems when multiple services is written in the same framwork and have a generic set of metrics. That is why there is a service label included. Normaly you should get the service name, from your service discovery.
to just view the code jump to he source link in the end of the page.
project structure
app.py starting the app with the python click framework to write a simple cli tool that takes some input to start the server
handler.py the handler holds the metric class that will be serving the metrics to prometheus when it’s collecting metrics. The on_get function uses the generate_latest function from the prometheus package to generate the body of the request. the generate_latest takes a class with a collect function that yields Metrics objects that holds a list of samples that is used to generate the body. Every Metrics object can hold more then just one metric if you have multiple metrics that is from the same metric like. requets-p99 requets-p95 requets-p90 and so on you shoud not export this metrics using the current name. It’s a more optimal to do this by using the labels and by translating them to a generic metric name. If metrics is exported in a format like response{latency="p99"}response{latency="p95"} . You can new do a promQL like this response{latency="p99"} to access this metrics.
prom.py A basic collector class with a collect function that gets called to generate the last metrics. it’s important to also allow for the option to exclude metrics when you are implementing a exporter to not add unwanted data. The _get_metrics function can just be replaced with a request to the system that you like to export metrics from to get prometheus native format. A suggestion here is to enrich the metrics like building a dict with the metrics you like to collect. By doing this you can select only a subset of the metrics the system exposes and you can enrich the metrics by adding extra labels and translate the metrics to a generic name used by all services to make the promQL’s more reusable over multiple service types.