Access Prometheus Python Client documentation
masterDetailed documentation, including API references and usage guides, is hosted at the official documentation site.
https://prometheus.github.io/client_pythonrepository·master·Indexed 26 days ago
https://github.com/prometheus/client_pythonThe official Python library for instrumenting applications with Prometheus metrics. It enables developers to expose application-specific metrics for scraping by a Prometheus server, providing built-in collectors for process metrics (Linux), Python runtime metadata, and garbage collection statistics. The library includes support for custom collectors, various metric families (Gauge, Counter, Summary), and a GraphiteBridge for pushing metrics to Graphite servers.
Detailed documentation, including API references and usage guides, is hosted at the official documentation site.
https://prometheus.github.io/client_pythonThis tutorial demonstrates how to install the client, instrument a function using a Summary metric, and start an HTTP server to expose those metrics to Prometheus.
pip install prometheus-client.Summary class to create a metric and the @metric.time() decorator to automatically track the number of calls and the total time spent in a function.start_http_server(port) to launch a background HTTP server that serves the metrics at the specified port.http://localhost:<port>/ in your browser.When using the @Summary.time() decorator, the following metrics are automatically generated:
<metric_name>_count: The total number of times the function was called.<metric_name>_sum: The total time spent in the function.On Linux systems, the client also provides process metrics (CPU, memory, etc.) automatically.
from prometheus_client import start_http_server, Summary
import random
import time
# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
"""A dummy function that takes some time."""
time.sleep(t)
if __name__ == '__main__':
# Start up the server to expose the metrics.
start_http_server(8000)
# Generate some requests.
while True:
process_request(random.random())The documentation uses the Geekdocs theme located in ./docs/themes/hugo-geekdoc/. To update to the latest release, remove the existing theme directory and download the latest version from the official releases. Note that there are no local modifications in the theme folder.
rm -rf ./docs/themes/hugo-geekdoc
mkdir -p themes/hugo-geekdoc/
curl -L https://github.com/thegeeklab/hugo-geekdoc/releases/latest/download/hugo-geekdoc.tar.gz | tar -xz -C themes/hugo-geekdoc/ --strip-components=1After setting up your Flask app with the DispatcherMiddleware as shown in the integration guide, you can run the application using uwsgi. Ensure you have uwsgi installed via pip.
# Install uwsgi if you do not have it
pip install uwsgi
uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable appUse start_wsgi_server(port) to serve Prometheus metrics using the WSGI reference implementation. This method starts a new thread to handle the HTTP server, allowing it to run alongside your main application.
from prometheus_client import start_wsgi_server
start_wsgi_server(8000)To avoid side effects in tests or to manage separate sets of metrics, you can create an isolated CollectorRegistry. When creating metrics, pass the custom registry instance to the registry argument to prevent them from being added to the global REGISTRY.
from prometheus_client import Counter, CollectorRegistry
# Create an isolated registry
r = CollectorRegistry()
# Register the counter specifically with the new registry
c2 = Counter('my_counter', 'A counter', registry=r)A Histogram samples observations and counts them in configurable buckets. Use it to track distributions such as request latency or response sizes, which allows you to calculate quantiles (e.g., p50, p95, p99) in Prometheus queries.
A Histogram exposes three time series per metric:
<name>_bucket{le="<bound>"}: Cumulative count of observations with value ≤ le.<name>_sum: Sum of all observed values.<name>_count: Total number of observations.from prometheus_client import Histogram
h = Histogram('request_latency_seconds', 'Description of histogram')
h.observe(4.7) # Observe 4.7 (seconds in this case)Use push_to_gateway to send metrics to a Prometheus Pushgateway. This is useful for ephemeral or batch jobs that cannot be scraped directly.
Note: It is recommended to use a separate CollectorRegistry instance to avoid pushing default process metrics (like CPU or memory) along with your custom metrics.
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)If you are using the Geekdoc Hugo theme from a cloned branch rather than a pre-built release tarball, you must manually build the required assets using npm and webpack. Follow these steps to install dependencies and generate the necessary assets:
package.json.# install required packages from package.json
npm install
# run the build script to build required assets
npm run build
# build release tarball
npm run packUse make_wsgi_app() to create a WSGI application that serves Prometheus metrics. This application can be integrated into existing WSGI-compliant web servers or frameworks. By default, the application respects Accept-Encoding:gzip headers and will compress responses if the header is present. To disable this compression, pass disable_compression=True to the function.
from prometheus_client import make_wsgi_app
from wsgiref.simple_server import make_server
app = make_wsgi_app()
httpd = make_server('', 8000, app)
httpd.serve_forever()A Summary samples observations and tracks the total count and sum of values. Use it to track the size or duration of events and compute averages.
Note: The Python client does not compute quantiles locally. If you require p50, p95, or p99 quantiles, use a Histogram instead.
A Summary exposes two time series per metric:
<name>_count: total number of observations<name>_sum: sum of all observed valuesfrom prometheus_client import Summary
s = Summary('request_latency_seconds', 'Description of summary')
s.observe(4.7) # Observe 4.7 (seconds in this case)By default, Counter, Histogram, and Summary metrics export an additional time series suffixed with _created containing the Unix timestamp of when the metric was initialized. To disable these series, you can either set the PROMETHEUS_DISABLE_CREATED_SERIES environment variable to True or call disable_created_metrics() in your Python code.
from prometheus_client import disable_created_metrics
disable_created_metrics()