Prometheus Flask Exporter
This library provides HTTP request metrics for Flask applications, allowing easy integration with Prometheus. It automatically collects default metrics like request duration and total counts, and enables defining custom metrics using decorators. The current version is 0.23.2, with new releases occurring periodically, often in response to updates in Flask or the underlying Prometheus client library.
Warnings
- deprecated The `group_by_endpoint` argument in `PrometheusMetrics` is deprecated.
- deprecated The `static_labels` argument in `PrometheusMetrics` is deprecated.
- gotcha Running Flask with `debug=True` (live-reloading) might not reflect metrics for the latest code unless the `DEBUG_METRICS` environment variable is set. Additionally, `PrometheusMetrics.start_http_server()` is not expected to work reliably in this debug scenario.
- gotcha Carefully manage metric label cardinality to avoid 'cardinality explosion', which can lead to excessive memory usage and Prometheus server crashes.
- breaking Past versions experienced issues due to breaking changes in the underlying `prometheus_client` library's `exposition` module (`choose_encoder`).
- gotcha Reports of memory leaks have been observed in specific pull-based Prometheus configurations when custom decorators for latency measurement are used.
Install
-
pip install prometheus-flask-exporter
Imports
- PrometheusMetrics
from prometheus_flask_exporter import PrometheusMetrics
- Flask
from flask import Flask
- request
from flask import request
Quickstart
from flask import Flask, request
from prometheus_flask_exporter import PrometheusMetrics
import os
app = Flask(__name__)
metrics = PrometheusMetrics(app)
# Optional: Add static info about the app
metrics.info('app_info', 'Application info', version='1.0.0')
@app.route('/')
def main():
return 'Hello World!'
@app.route('/long-running')
@metrics.gauge('in_progress', 'Long running requests in progress')
def long_running():
import time
time.sleep(2)
return 'Done!'
# Run the app directly or using a WSGI server like Gunicorn
if __name__ == '__main__':
# Example: Access http://localhost:5000/ and http://localhost:5000/metrics
app.run(host='0.0.0.0', port=5000)