Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created August 15, 2019 06:34
Show Gist options
  • Save amitsaha/794c066856de4810c0863f0501fd1245 to your computer and use it in GitHub Desktop.
Save amitsaha/794c066856de4810c0863f0501fd1245 to your computer and use it in GitHub Desktop.
test python + prometheus
from prometheus_client import multiprocess
from prometheus_client import generate_latest, CollectorRegistry, CONTENT_TYPE_LATEST, Gauge
from flask import Flask, Response
app = Flask(__name__)
from flask import request
from prometheus_client import Counter, Histogram
import time
import sys
REQUEST_COUNT = Counter(
'request_count', 'App Request Count',
['app_name', 'method', 'endpoint', 'http_status']
)
REQUEST_LATENCY = Histogram('request_latency_seconds', 'Request latency',
['app_name', 'endpoint']
)
def start_timer():
request.start_time = time.time()
def stop_timer(response):
resp_time = time.time() - request.start_time
REQUEST_LATENCY.labels('webapp', request.path).observe(resp_time)
return response
def record_request_data(response):
REQUEST_COUNT.labels('webapp', request.method, request.path,
response.status_code).inc()
return response
def setup_metrics(app):
app.before_request(start_timer)
# The order here matters since we want stop_timer
# to be executed first
app.after_request(record_request_data)
app.after_request(stop_timer)
@app.route('/test/')
def test():
return 'rest'
@app.route('/test1/')
def test1():
1/0
return 'rest'
@app.errorhandler(500)
def handle_500(error):
return str(error), 500
@app.route('/metrics')
def metrics():
"""
View the metrics sent to prometheus servers.
"""
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
data = generate_latest(registry)
print(data)
response_headers = [
('Content-type', CONTENT_TYPE_LATEST),
('Content-Length', str(len(data)))
]
return Response(response=data, status=200, headers=response_headers)
if __name__ == '__main__':
setup_metrics(app)
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment