Skip to content

Instantly share code, notes, and snippets.

@synergit
Last active July 9, 2021 03:34
Show Gist options
  • Select an option

  • Save synergit/e61b7250578c40b5872eae5dd4ef0458 to your computer and use it in GitHub Desktop.

Select an option

Save synergit/e61b7250578c40b5872eae5dd4ef0458 to your computer and use it in GitHub Desktop.
import http.server
import time
# (1) Make sure prometheus_client is installed
from prometheus_client import start_http_server, Gauge
REQUEST_INPROGRESS = Gauge('app_request_inprogress', 'application request in progress')
APP_PORT = 8000 # (2) define application port
METRICS_PORT = 8001 # (3) define metrics port
class HandleRequests(http.server.BaseHTTPRequestHandler):
@REQUEST_INPROGRESS.track_inprogress() # (4) one way to instrument with Gauge
def do_GET(self):
# (5.1) the second way to instrument with Gauge. Call inc() first
# REQUEST_INPROGRESS.inc()
# (6) make the request takes longer so that you will see the difference when you do the query
time.sleep(5)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>A Taste of Prometheus</title></head><body><h2>welcome</h2></body></html>", "utf-8"))
self.wfile.flush()
# (5.2) the second way to instrument with Gauge. Call dec() when the request complete
# REQUEST_INPROGRESS.dec()
if __name__ == "__main__":
# (7) start the server for exposing metrics
start_http_server(METRICS_PORT)
# (8) start the web application server
server = http.server.HTTPServer(('localhost', APP_PORT), HandleRequests)
server.serve_forever()
@synergit
Copy link
Copy Markdown
Author

synergit commented Jul 9, 2021

medium blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment