Skip to content

Commit

Permalink
Add status code.
Browse files Browse the repository at this point in the history
  • Loading branch information
philwinder committed Nov 11, 2017
1 parent 85911b1 commit c2b11df
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import random
import time

from flask import Flask, render_template_string
from flask import Flask, render_template_string, abort
from prometheus_client import generate_latest, REGISTRY, Counter, Gauge, Histogram

app = Flask(__name__)

# A counter to count the total number of HTTP requests
REQUESTS = Counter('http_request_total', 'Total HTTP Requests (count)', ['method', 'endpoint'])
REQUESTS = Counter('http_request_total', 'Total HTTP Requests (count)', ['method', 'endpoint', 'status_code'])

# A gauge (i.e. goes up and down) to monitor the total number of in progress requests
IN_PROGRESS = Gauge('http_request_inprogress', 'Number of in progress HTTP requests')
Expand All @@ -23,33 +23,36 @@
# Helper annotation to increment a gauge when entering the method and decrementing when leaving.
@IN_PROGRESS.track_inprogress()
def hello_world():
REQUESTS.labels(method='GET', endpoint="/").inc() # Increment the counter
REQUESTS.labels(method='GET', endpoint="/", status_code=200).inc() # Increment the counter
return 'Hello, World!'


# Note I'm intentionally failing occasionally to simulate a flakey service.
@app.route('/slow')
@TIMINGS.time()
@IN_PROGRESS.track_inprogress()
def slow_request():
REQUESTS.labels(method='GET', endpoint="/slow").inc()
v = random.expovariate(1.0 / 1.3)
if v > 3:
REQUESTS.labels(method='GET', endpoint="/slow", status_code=500).inc()
abort(500)
time.sleep(v)
REQUESTS.labels(method='GET', endpoint="/slow", status_code=200).inc()
return render_template_string('<h1>Wow, that took {{v}} s!</h1>', v=v)


@app.route('/hello/<name>')
@IN_PROGRESS.track_inprogress()
@TIMINGS.time()
def index(name):
REQUESTS.labels(method='GET', endpoint="/hello/<name>").inc()
REQUESTS.labels(method='GET', endpoint="/hello/<name>", status_code=200).inc()
return render_template_string('<b>Hello {{name}}</b>!', name=name)


@app.route('/metrics')
@IN_PROGRESS.track_inprogress()
@TIMINGS.time()
def metrics():
REQUESTS.labels(method='GET', endpoint="/metrics").inc()
REQUESTS.labels(method='GET', endpoint="/metrics", status_code=200).inc()
return generate_latest(REGISTRY)


Expand Down

0 comments on commit c2b11df

Please sign in to comment.