I wanted to use a Raspberry Pi and some sensors to create a Grafana dashboard for monitoring air quality. I didn’t like the idea of using any library to keep everything simple, and I wanted to learn how Prometheus works.
Prometheus will look for <hostname>/metrics to collect metrics, and it has to be in the format below.
one_sensor 0.5
second_sensor 100
It should respond with a 200 status code too. I wrote a second exporter without a 200 status code and it failed. You can use the code below to make it work.
from http.server import BaseHTTPRequestHandler, HTTPServer
class BaseHandler(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
def do_GET(self):
self._set_response()
result = "first_metric 1\n"
result = result + "second_metric 2\n"
output = process(result.stdout.strip())
self.wfile.write(output.encode("utf-8"))
def run(server_class=HTTPServer, handler_class=BaseHandler, port=9123):
server_address = ("0.0.0.0", port)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
If you want to install it as a service, you can use this file.
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target
[Service]
User=user1
Group=user1
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/python3 /home/user1/app.py
[Install]
WantedBy=multi-user.target




