|
| 1 | +import random |
| 2 | +import time |
| 3 | + |
| 4 | +from flask import Flask, render_template_string |
| 5 | +from prometheus_client import generate_latest, REGISTRY, Counter, Gauge, Histogram |
| 6 | + |
| 7 | +app = Flask(__name__) |
| 8 | + |
| 9 | +# A counter to count the total number of HTTP requests |
| 10 | +REQUESTS = Counter('http_requests_total', 'Total HTTP Requests (count)', ['method', 'endpoint']) |
| 11 | + |
| 12 | +# A gauge (i.e. goes up and down) to monitor the total number of in progress requests |
| 13 | +IN_PROGRESS = Gauge('http_requests_inprogress', 'Number of in progress HTTP requests') |
| 14 | + |
| 15 | +# A histogram to measure the latency of the HTTP requests |
| 16 | +TIMINGS = Histogram('http_requests_latency_seconds', 'HTTP request latency (seconds)') |
| 17 | + |
| 18 | + |
| 19 | +# Standard Flask route stuff. |
| 20 | +@app.route('/') |
| 21 | +# Helper annotation to measure how long a method takes and save as a histogram metric. |
| 22 | +@TIMINGS.time() |
| 23 | +# Helper annotation to increment a gauge when entering the method and decrementing when leaving. |
| 24 | +@IN_PROGRESS.track_inprogress() |
| 25 | +def hello_world(): |
| 26 | + REQUESTS.labels(method='GET', endpoint="/").inc() # Increment the counter |
| 27 | + return 'Hello, World!' |
| 28 | + |
| 29 | + |
| 30 | +@app.route('/slow') |
| 31 | +@TIMINGS.time() |
| 32 | +@IN_PROGRESS.track_inprogress() |
| 33 | +def slow_request(): |
| 34 | + REQUESTS.labels(method='GET', endpoint="/slow").inc() |
| 35 | + v = random.random() |
| 36 | + time.sleep(v) |
| 37 | + return render_template_string('<h1>Wow, that took {{v}} s!</h1>', v=v) |
| 38 | + |
| 39 | + |
| 40 | +@app.route('/hello/<name>') |
| 41 | +@IN_PROGRESS.track_inprogress() |
| 42 | +@TIMINGS.time() |
| 43 | +def index(name): |
| 44 | + REQUESTS.labels(method='GET', endpoint="/hello/<name>").inc() |
| 45 | + return render_template_string('<b>Hello {{name}}</b>!', name=name) |
| 46 | + |
| 47 | + |
| 48 | +@app.route('/metrics') |
| 49 | +@IN_PROGRESS.track_inprogress() |
| 50 | +@TIMINGS.time() |
| 51 | +def metrics(): |
| 52 | + REQUESTS.labels(method='GET', endpoint="/metrics").inc() |
| 53 | + return generate_latest(REGISTRY) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + app.run(host='0.0.0.0') |
0 commit comments