|
1 | 1 | import random |
2 | 2 | import time |
3 | 3 |
|
4 | | -from flask import Flask, render_template_string |
| 4 | +from flask import Flask, render_template_string, abort |
5 | 5 | from prometheus_client import generate_latest, REGISTRY, Counter, Gauge, Histogram |
6 | 6 |
|
7 | 7 | app = Flask(__name__) |
8 | 8 |
|
9 | 9 | # A counter to count the total number of HTTP requests |
10 | | -REQUESTS = Counter('http_request_total', 'Total HTTP Requests (count)', ['method', 'endpoint']) |
| 10 | +REQUESTS = Counter('http_request_total', 'Total HTTP Requests (count)', ['method', 'endpoint', 'status_code']) |
11 | 11 |
|
12 | 12 | # A gauge (i.e. goes up and down) to monitor the total number of in progress requests |
13 | 13 | IN_PROGRESS = Gauge('http_request_inprogress', 'Number of in progress HTTP requests') |
|
23 | 23 | # Helper annotation to increment a gauge when entering the method and decrementing when leaving. |
24 | 24 | @IN_PROGRESS.track_inprogress() |
25 | 25 | def hello_world(): |
26 | | - REQUESTS.labels(method='GET', endpoint="/").inc() # Increment the counter |
| 26 | + REQUESTS.labels(method='GET', endpoint="/", status_code=200).inc() # Increment the counter |
27 | 27 | return 'Hello, World!' |
28 | 28 |
|
29 | | - |
| 29 | +# Note I'm intentionally failing occasionally to simulate a flakey service. |
30 | 30 | @app.route('/slow') |
31 | 31 | @TIMINGS.time() |
32 | 32 | @IN_PROGRESS.track_inprogress() |
33 | 33 | def slow_request(): |
34 | | - REQUESTS.labels(method='GET', endpoint="/slow").inc() |
35 | 34 | v = random.expovariate(1.0 / 1.3) |
| 35 | + if v > 3: |
| 36 | + REQUESTS.labels(method='GET', endpoint="/slow", status_code=500).inc() |
| 37 | + abort(500) |
36 | 38 | time.sleep(v) |
| 39 | + REQUESTS.labels(method='GET', endpoint="/slow", status_code=200).inc() |
37 | 40 | return render_template_string('<h1>Wow, that took {{v}} s!</h1>', v=v) |
38 | 41 |
|
39 | 42 |
|
40 | 43 | @app.route('/hello/<name>') |
41 | 44 | @IN_PROGRESS.track_inprogress() |
42 | 45 | @TIMINGS.time() |
43 | 46 | def index(name): |
44 | | - REQUESTS.labels(method='GET', endpoint="/hello/<name>").inc() |
| 47 | + REQUESTS.labels(method='GET', endpoint="/hello/<name>", status_code=200).inc() |
45 | 48 | return render_template_string('<b>Hello {{name}}</b>!', name=name) |
46 | 49 |
|
47 | 50 |
|
48 | 51 | @app.route('/metrics') |
49 | 52 | @IN_PROGRESS.track_inprogress() |
50 | 53 | @TIMINGS.time() |
51 | 54 | def metrics(): |
52 | | - REQUESTS.labels(method='GET', endpoint="/metrics").inc() |
| 55 | + REQUESTS.labels(method='GET', endpoint="/metrics", status_code=200).inc() |
53 | 56 | return generate_latest(REGISTRY) |
54 | 57 |
|
55 | 58 |
|
|
0 commit comments