Skip to content

Commit c2b11df

Browse files
committed
Add status code.
1 parent 85911b1 commit c2b11df

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

app.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import random
22
import time
33

4-
from flask import Flask, render_template_string
4+
from flask import Flask, render_template_string, abort
55
from prometheus_client import generate_latest, REGISTRY, Counter, Gauge, Histogram
66

77
app = Flask(__name__)
88

99
# 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'])
1111

1212
# A gauge (i.e. goes up and down) to monitor the total number of in progress requests
1313
IN_PROGRESS = Gauge('http_request_inprogress', 'Number of in progress HTTP requests')
@@ -23,33 +23,36 @@
2323
# Helper annotation to increment a gauge when entering the method and decrementing when leaving.
2424
@IN_PROGRESS.track_inprogress()
2525
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
2727
return 'Hello, World!'
2828

29-
29+
# Note I'm intentionally failing occasionally to simulate a flakey service.
3030
@app.route('/slow')
3131
@TIMINGS.time()
3232
@IN_PROGRESS.track_inprogress()
3333
def slow_request():
34-
REQUESTS.labels(method='GET', endpoint="/slow").inc()
3534
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)
3638
time.sleep(v)
39+
REQUESTS.labels(method='GET', endpoint="/slow", status_code=200).inc()
3740
return render_template_string('<h1>Wow, that took {{v}} s!</h1>', v=v)
3841

3942

4043
@app.route('/hello/<name>')
4144
@IN_PROGRESS.track_inprogress()
4245
@TIMINGS.time()
4346
def index(name):
44-
REQUESTS.labels(method='GET', endpoint="/hello/<name>").inc()
47+
REQUESTS.labels(method='GET', endpoint="/hello/<name>", status_code=200).inc()
4548
return render_template_string('<b>Hello {{name}}</b>!', name=name)
4649

4750

4851
@app.route('/metrics')
4952
@IN_PROGRESS.track_inprogress()
5053
@TIMINGS.time()
5154
def metrics():
52-
REQUESTS.labels(method='GET', endpoint="/metrics").inc()
55+
REQUESTS.labels(method='GET', endpoint="/metrics", status_code=200).inc()
5356
return generate_latest(REGISTRY)
5457

5558

0 commit comments

Comments
 (0)