Skip to content

Instantly share code, notes, and snippets.

@rchakode
Last active May 12, 2022 14:07
Show Gist options
  • Save rchakode/a992f1a3780e449ec040a1b6ca51c33f to your computer and use it in GitHub Desktop.
Save rchakode/a992f1a3780e449ec040a1b6ca51c33f to your computer and use it in GitHub Desktop.
Example Prometheus exporter that exports metrics of a Flask application
import prometheus_client
import werkzeug.wsgi
import flask
import random
import time
import threading
SERVICE_UPTIME = prometheus_client.Gauge('service_uptime',
'Hold the time elasted since service startup')
RESPONSE_TIME = prometheus_client.Gauge('response_time_last',
'Hold the last request response time')
# Create Flask app
app = flask.Flask(__name__)
@app.route('/')
@RESPONSE_TIME.time()
def hello():
time.sleep(random.random())
return "Hello World!"
# Prometheus wsgi middleware to route /metrics requests
app_dispatch = werkzeug.wsgi.DispatcherMiddleware(app, {
'/metrics': prometheus_client.make_wsgi_app()
})
def update_uptime():
while True:
SERVICE_UPTIME.inc(1)
time.sleep(1)
SERVICE_UPTIME.set(0)
uptime_updater = threading.Thread(target=update_uptime)
uptime_updater.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment