Skip to content

Commit

Permalink
refactor: move bulk of prometheus setup in server.py to metrics.py
Browse files Browse the repository at this point in the history
  • Loading branch information
brentvollebregt committed Jul 26, 2020
1 parent 5efcf29 commit a48386e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
14 changes: 12 additions & 2 deletions metrics.py
@@ -1,7 +1,8 @@
import time
from threading import Lock, Timer

from prometheus_client import Gauge
from prometheus_client import Gauge, make_wsgi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware

import config

Expand All @@ -14,12 +15,21 @@
lock = Lock()


def init_metrics(db_connection):
def init_metrics(app, db_connection):
"""
Initialise Prometheus Metrics
:param app: Flask app to serve metrics at `/metrics` from
:param db_connection: Connection to the database to get stats
"""
g = Gauge(f'{METRICS_PREFIX}_hits_total', 'Total number of hits', ['site', 'path'])
register_labels(db_connection, g)

Timer(REGISTER_INTERVAL_SEC, lambda: register_labels(db_connection, g)).start()

app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
'/metrics': make_wsgi_app()
})


def register_labels(db_connection, gauge):
url_counts = db_connection.get_top_urls(db_connection.get_connection(), -1)
Expand Down
7 changes: 1 addition & 6 deletions server.py
Expand Up @@ -14,13 +14,8 @@

# Prometheus metrics
if config.EXPOSE_METRICS:
from prometheus_client import make_wsgi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from metrics import init_metrics
init_metrics(db_connection)
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
'/metrics': make_wsgi_app()
})
init_metrics(app, db_connection)


def make_text_response(count, url, cookie_required):
Expand Down

0 comments on commit a48386e

Please sign in to comment.