### Start HTTPS Server Source: https://prometheus.github.io/client_python/exporting/http Starts an HTTPS server by providing the required certificate and key files. ```python from prometheus_client import start_http_server start_http_server(8000, certfile="server.crt", keyfile="server.key") ``` -------------------------------- ### Real-world Application Metadata Example Source: https://prometheus.github.io/client_python/instrumenting/info Full example demonstrating how to expose build metadata via an HTTP server. ```python from prometheus_client import Info, start_http_server BUILD_INFO = Info( 'build', 'Application build information', namespace='myapp', ) BUILD_INFO.info({ 'version': '1.4.2', 'revision': 'abc123def456', 'branch': 'main', 'build_date': '2024-01-15', }) if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### Real-world Gauge Example Source: https://prometheus.github.io/client_python/instrumenting/gauge Complete example demonstrating active connection tracking and queue size monitoring. ```python from prometheus_client import Gauge, start_http_server ACTIVE_CONNECTIONS = Gauge( 'connections_active', 'Number of active database connections', namespace='myapp', ) QUEUE_SIZE = Gauge( 'job_queue_size', 'Number of jobs waiting in the queue', namespace='myapp', ) job_queue = [] QUEUE_SIZE.set_function(lambda: len(job_queue)) def acquire_connection(): ACTIVE_CONNECTIONS.inc() def release_connection(): ACTIVE_CONNECTIONS.dec() if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### Install Prometheus Python Client Source: https://prometheus.github.io/client_python Use pip to install the required library for Prometheus metrics instrumentation. ```bash pip install prometheus-client ``` -------------------------------- ### Instrument Python Application Source: https://prometheus.github.io/client_python Example of creating a Summary metric, decorating a function to track execution time, and starting an HTTP server to expose metrics on port 8000. ```python 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()) ``` -------------------------------- ### Run Flask Application with uWSGI Source: https://prometheus.github.io/client_python/exporting/http/flask Commands to install uWSGI and serve the Flask application. ```bash # Install uwsgi if you do not have it pip install uwsgi uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable app ``` -------------------------------- ### start_wsgi_server Source: https://prometheus.github.io/client_python/exporting/http/wsgi Starts a WSGI server in a new thread to serve Prometheus metrics. ```APIDOC ## start_wsgi_server(port) ### Description Starts a WSGI server using the reference implementation in a new thread to serve metrics on the specified port. ### Parameters - **port** (int) - Required - The port number to bind the server to. ### Example ```python from prometheus_client import start_wsgi_server start_wsgi_server(8000) ``` ``` -------------------------------- ### Start HTTP Server Source: https://prometheus.github.io/client_python/exporting/http Starts a daemon thread HTTP server on the specified port to expose metrics. ```python from prometheus_client import start_http_server start_http_server(8000) ``` -------------------------------- ### Add Summary Metrics Source: https://prometheus.github.io/client_python/collector/custom Example of adding labelled samples to a SummaryMetricFamily. ```python s = SummaryMetricFamily('rpc_duration_seconds', 'RPC duration', labels=['method']) s.add_metric(['get'], count_value=1000, sum_value=53.2) s.add_metric(['put'], count_value=400, sum_value=28.7) yield s ``` -------------------------------- ### Metric Name Construction Source: https://prometheus.github.io/client_python/instrumenting/info Example showing how namespace, subsystem, and name parameters combine to form the final metric name. ```python # namespace='myapp', subsystem='http', name='build' # produces: myapp_http_build_info Info('build', 'Build information', namespace='myapp', subsystem='http') ``` -------------------------------- ### Add Counter Metrics Source: https://prometheus.github.io/client_python/collector/custom Example of adding labelled samples to a CounterMetricFamily. ```python c = CounterMetricFamily('http_requests_total', 'HTTP requests by status', labels=['status']) c.add_metric(['200'], 1200) c.add_metric(['404'], 43) c.add_metric(['500'], 7) yield c ``` -------------------------------- ### Track Background Task Duration Source: https://prometheus.github.io/client_python/instrumenting/summary A complete example showing how to use labels and the time() context manager for background tasks. ```python from prometheus_client import Summary, start_http_server TASK_DURATION = Summary( 'task_duration_seconds', 'Time spent processing background tasks', labelnames=['task_type'], namespace='myapp', ) def run_task(task_type, task): with TASK_DURATION.labels(task_type=task_type).time(): # ... run the task ... pass if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### Add Gauge Metrics Source: https://prometheus.github.io/client_python/collector/custom Example of adding labelled samples to a GaugeMetricFamily. ```python g = GaugeMetricFamily('temperature_celsius', 'Temperature by location', labels=['location']) g.add_metric(['living_room'], 21.5) g.add_metric(['basement'], 18.0) yield g ``` -------------------------------- ### Create labelled InfoMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Example of creating a labelled info metric and adding multiple service-specific entries. ```python i = InfoMetricFamily('service_build', 'Per-service build info', labels=['service']) i.add_metric(['auth'], {'version': '2.0.1', 'commit': 'def456'}) i.add_metric(['api'], {'version': '1.9.0', 'commit': 'ghi789'}) yield i ``` -------------------------------- ### GET (any) Source: https://prometheus.github.io/client_python/exporting/http Returns HTTP status 200 and the metrics data. ```APIDOC ## GET (any) ### Description Returns HTTP status 200 and the metrics data. ### Method GET ### Endpoint (any) ``` -------------------------------- ### Real-world Histogram Implementation Source: https://prometheus.github.io/client_python/instrumenting/histogram Full example of tracking HTTP request latency with labels and custom buckets. ```python from prometheus_client import Histogram, start_http_server REQUEST_LATENCY = Histogram( 'request_duration_seconds', 'HTTP request latency', labelnames=['method', 'endpoint'], namespace='myapp', buckets=[.01, .05, .1, .25, .5, 1, 2.5, 5], ) def handle_request(method, endpoint): with REQUEST_LATENCY.labels(method=method, endpoint=endpoint).time(): # ... handle the request ... pass if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### OPTIONS (any) Source: https://prometheus.github.io/client_python/exporting/http Returns HTTP status 200 and an 'Allow' header indicating the allowed methods (OPTIONS, GET). ```APIDOC ## OPTIONS (any) ### Description Returns HTTP status 200 and an 'Allow' header indicating the allowed methods (OPTIONS, GET). ### Method OPTIONS ### Endpoint (any) ``` -------------------------------- ### Start a WSGI server in a new thread Source: https://prometheus.github.io/client_python/exporting/http/wsgi Serves metrics through the WSGI reference implementation in a background thread. ```python from prometheus_client import start_wsgi_server start_wsgi_server(8000) ``` -------------------------------- ### Create unlabelled InfoMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Example of yielding a single unlabelled info metric with key-value pairs. ```python yield InfoMetricFamily('build', 'Build metadata', value={'version': '1.2.3', 'commit': 'abc123'}) ``` -------------------------------- ### Running FastAPI with Gunicorn Source: https://prometheus.github.io/client_python/exporting/http/fastapi-gunicorn Command to start the FastAPI application using the Uvicorn worker class for Gunicorn. ```bash # Install gunicorn if you do not have it pip install gunicorn # If using multiple workers, add `--workers n` parameter to the line below gunicorn -b 127.0.0.1:8000 myapp:app -k uvicorn.workers.UvicornWorker ``` -------------------------------- ### Track background worker lifecycle Source: https://prometheus.github.io/client_python/instrumenting/enum A complete example demonstrating how to track the state of a background worker process. ```python from prometheus_client import Enum, start_http_server WORKER_STATE = Enum( 'worker_state', 'Current state of the background worker', states=['idle', 'running', 'error'], namespace='myapp', ) def process_job(): WORKER_STATE.state('running') try: # ... do work ... pass except Exception: WORKER_STATE.state('error') raise finally: WORKER_STATE.state('idle') if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### Track HTTP requests with labels Source: https://prometheus.github.io/client_python/instrumenting/counter Real-world example demonstrating how to use labels with Counters to track HTTP requests and exceptions. ```python from prometheus_client import Counter, start_http_server REQUESTS = Counter( 'requests_total', 'Total HTTP requests received', labelnames=['method', 'status'], namespace='myapp', ) EXCEPTIONS = Counter( 'exceptions_total', 'Total unhandled exceptions', labelnames=['handler'], namespace='myapp', ) def handle_request(method, handler): with EXCEPTIONS.labels(handler=handler).count_exceptions(): # ... process the request ... status = '200' REQUESTS.labels(method=method, status=status).inc() if __name__ == '__main__': start_http_server(8000) # exposes metrics at http://localhost:8000/metrics # ... start your application ... ``` -------------------------------- ### Add metrics to HistogramMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Example of creating a labelled histogram and adding metric data points. ```python h = HistogramMetricFamily('request_size_bytes', 'Request sizes', labels=['handler']) h.add_metric( ['api'], buckets=[('100', 5), ('1000', 42), ('+Inf', 50)], sum_value=18350.0, ) yield h ``` -------------------------------- ### Get target info labels Source: https://prometheus.github.io/client_python/registry Retrieves the current target metadata labels. ```python info = REGISTRY.get_target_info() ``` -------------------------------- ### HTTP Error Response Example Source: https://prometheus.github.io/client_python/exporting/http Shows the format of an HTTP error response returned by the client. ```text # HTTP 405 Method Not Allowed: XXX; use OPTIONS or GET ``` -------------------------------- ### Summary Metric Output Format Source: https://prometheus.github.io/client_python/instrumenting/summary Example of the time series data produced by a Summary metric. ```text myapp_task_duration_seconds_count{task_type="email"} 120 myapp_task_duration_seconds_sum{task_type="email"} 48.3 ``` -------------------------------- ### Example restricted output Source: https://prometheus.github.io/client_python/restricted-registry The resulting output format when a registry is restricted to specific metrics. ```text # HELP python_info Python platform information # TYPE python_info gauge python_info{implementation="CPython",major="3",minor="9",patchlevel="3",version="3.9.3"} 1.0 # HELP python_gc_objects_collected_total Objects collected during gc # TYPE python_gc_objects_collected_total counter python_gc_objects_collected_total{generation="0"} 73129.0 python_gc_objects_collected_total{generation="1"} 8594.0 python_gc_objects_collected_total{generation="2"} 296.0 ``` -------------------------------- ### Enum naming convention Source: https://prometheus.github.io/client_python/instrumenting/enum Example of how namespace, subsystem, and name parameters combine to form the final metric name. ```python # namespace='myapp', subsystem='worker', name='state' # produces: myapp_worker_state Enum('state', 'Worker state', states=['idle', 'running', 'error'], namespace='myapp', subsystem='worker') ``` -------------------------------- ### Histogram Output Format Source: https://prometheus.github.io/client_python/instrumenting/histogram Example of the time series generated by a histogram with labels. ```text myapp_request_duration_seconds_bucket{method="GET",endpoint="/api/users",le="0.1"} 42 myapp_request_duration_seconds_sum{method="GET",endpoint="/api/users"} 3.7 myapp_request_duration_seconds_count{method="GET",endpoint="/api/users"} 50 ``` -------------------------------- ### GET /favicon.ico Source: https://prometheus.github.io/client_python/exporting/http Returns HTTP status 200 and an empty response body. ```APIDOC ## GET /favicon.ico ### Description Returns HTTP status 200 and an empty response body. Some browsers support this to display the returned icon in the browser tab. ### Method GET ### Endpoint /favicon.ico ``` -------------------------------- ### Get sample value for testing Source: https://prometheus.github.io/client_python/registry Retrieves the current value of a specific metric sample, primarily for unit testing. ```python from prometheus_client import Counter, CollectorRegistry r = CollectorRegistry() c = Counter('requests_total', 'Total requests', registry=r) c.inc(3) assert r.get_sample_value('requests_total') == 3.0 ``` -------------------------------- ### Initialize and Observe a Summary Source: https://prometheus.github.io/client_python/instrumenting/summary Create a Summary metric and record observations using the observe method. ```python from prometheus_client import Summary s = Summary('request_latency_seconds', 'Description of summary') s.observe(4.7) # Observe 4.7 (seconds in this case) ``` -------------------------------- ### Define Summary with Namespace and Subsystem Source: https://prometheus.github.io/client_python/instrumenting/summary Demonstrates how namespace, subsystem, and name parameters combine to form the full metric name. ```python # namespace='myapp', subsystem='worker', name='task_duration_seconds' # produces: myapp_worker_task_duration_seconds Summary('task_duration_seconds', 'Task duration', namespace='myapp', subsystem='worker') ``` -------------------------------- ### Create an ASGI application for Prometheus metrics Source: https://prometheus.github.io/client_python/exporting/http/asgi Initializes a basic ASGI application to serve Prometheus metrics. ```python from prometheus_client import make_asgi_app app = make_asgi_app() ``` -------------------------------- ### Initialize SummaryMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Constructor signature for SummaryMetricFamily. ```python SummaryMetricFamily(name, documentation, count_value=None, sum_value=None, labels=None, unit='') ``` -------------------------------- ### Initialize InfoMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Constructor signature for creating a new Info metric family. ```python InfoMetricFamily(name, documentation, value=None, labels=None) ``` -------------------------------- ### Create a WSGI application for metrics Source: https://prometheus.github.io/client_python/exporting/http/wsgi Uses make_wsgi_app to generate a WSGI app and serves it using wsgiref.simple_server. ```python 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() ``` -------------------------------- ### Initialize CounterMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Constructor signature for CounterMetricFamily. ```python CounterMetricFamily(name, documentation, value=None, labels=None, created=None, unit='', exemplar=None) ``` -------------------------------- ### Info(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) Source: https://prometheus.github.io/client_python/instrumenting/info Constructor for creating an Info metric instance. ```APIDOC ## Constructor: Info ### Description Initializes a new Info metric. A '_info' suffix is automatically appended to the metric name. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text for the metric. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Not supported; raises ValueError. - **registry** (CollectorRegistry) - Optional - Registry to register with. ``` -------------------------------- ### Initialize CollectorRegistry constructor Source: https://prometheus.github.io/client_python/registry Shows the signature for creating a new CollectorRegistry instance. ```python CollectorRegistry(auto_describe=False, target_info=None, support_collectors_without_names=False) ``` -------------------------------- ### Global REGISTRY initialization Source: https://prometheus.github.io/client_python/registry Shows how the default global REGISTRY instance is initialized. ```python REGISTRY = CollectorRegistry(auto_describe=True) ``` -------------------------------- ### Summary(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) Source: https://prometheus.github.io/client_python/instrumenting/summary Constructor for creating a new Summary metric instance. ```APIDOC ## Summary Constructor ### Description Creates a new Summary metric to track observations. The full metric name is formed by joining namespace, subsystem, and name with underscores. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text shown in the /metrics output. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Optional unit suffix. - **registry** (CollectorRegistry) - Optional - Registry to register with. ``` -------------------------------- ### Using instance IP grouping key Source: https://prometheus.github.io/client_python/exporting/pushgateway Automatically set the instance label to the host's IP address using the instance_ip_grouping_key helper. ```python from prometheus_client.exposition import instance_ip_grouping_key push_to_gateway('localhost:9091', job='batchA', registry=registry, grouping_key=instance_ip_grouping_key()) ``` -------------------------------- ### Initialize GaugeMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Constructor signature for GaugeMetricFamily. ```python GaugeMetricFamily(name, documentation, value=None, labels=None, unit='') ``` -------------------------------- ### Initialize and use CollectorRegistry Source: https://prometheus.github.io/client_python/registry Demonstrates using the default global registry versus creating an isolated registry for testing purposes. ```python from prometheus_client import REGISTRY, CollectorRegistry # Use the default global registry from prometheus_client import Counter c = Counter('my_counter', 'A counter') # registered with REGISTRY automatically # Create an isolated registry, e.g. for testing r = CollectorRegistry() c2 = Counter('my_counter', 'A counter', registry=r) ``` -------------------------------- ### Construct Counter with namespace and subsystem Source: https://prometheus.github.io/client_python/instrumenting/counter Demonstrates how namespace, subsystem, and name parameters are combined into the final metric name. ```python # namespace='myapp', subsystem='http', name='requests_total' # produces: myapp_http_requests_total Counter('requests_total', 'Total requests', namespace='myapp', subsystem='http') ``` -------------------------------- ### Export metrics to a text file Source: https://prometheus.github.io/client_python/exporting/textfile Demonstrates creating a custom registry and writing metrics to a file for the Node exporter to collect. ```python from prometheus_client import CollectorRegistry, Gauge, write_to_textfile registry = CollectorRegistry() g = Gauge('raid_status', '1 if raid array is okay', registry=registry) g.set(1) write_to_textfile('/configured/textfile/path/raid.prom', registry) ``` -------------------------------- ### Basic Info Metric Usage Source: https://prometheus.github.io/client_python/instrumenting/info Initialize an Info metric and set its key-value pairs. ```python from prometheus_client import Info i = Info('my_build_version', 'Description of info') i.info({'version': '1.2.3', 'buildhost': 'foo@bar'}) ``` -------------------------------- ### make_asgi_app Source: https://prometheus.github.io/client_python/exporting/http/asgi Creates an ASGI application to serve Prometheus metrics. ```APIDOC ## make_asgi_app ### Description Creates an ASGI application that exposes Prometheus metrics. This application can be integrated into existing ASGI frameworks. ### Parameters - **disable_compression** (bool) - Optional - If set to True, disables Gzip compression of the response even if the client sends an Accept-Encoding: gzip header. Defaults to False. ### Usage Example ```python from prometheus_client import make_asgi_app # Basic usage app = make_asgi_app() # Usage with compression disabled app = make_asgi_app(disable_compression=True) ``` ``` -------------------------------- ### Summary Constructor Signature Source: https://prometheus.github.io/client_python/instrumenting/summary The signature for initializing a new Summary metric. ```python Summary(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) ``` -------------------------------- ### Shutdown HTTP Server Source: https://prometheus.github.io/client_python/exporting/http Demonstrates how to gracefully shut down the server and join the daemon thread. ```python server, t = start_http_server(8000) server.shutdown() server.server_close() t.join() ``` -------------------------------- ### Constructing GaugeMetricFamily with inline or labelled data Source: https://prometheus.github.io/client_python/collector/custom Demonstrates initializing a GaugeMetricFamily with a single unlabelled value versus using labels to add multiple metrics. ```python # single unlabelled value GaugeMetricFamily('my_gauge', 'Help text', value=7) # labelled metrics via add_metric g = GaugeMetricFamily('my_gauge', 'Help text', labels=['region']) g.add_metric(['us-east-1'], 3) g.add_metric(['eu-west-1'], 5) ``` -------------------------------- ### Initialize HistogramMetricFamily Source: https://prometheus.github.io/client_python/collector/custom Constructor signature for creating a new Histogram metric family. ```python HistogramMetricFamily(name, documentation, buckets=None, sum_value=None, labels=None, unit='') ``` -------------------------------- ### Register a custom collector Source: https://prometheus.github.io/client_python/registry Shows how to implement and register a custom collector class. ```python from prometheus_client.registry import Collector class MyCollector(Collector): def collect(self): ... REGISTRY.register(MyCollector()) ``` -------------------------------- ### Basic Histogram Usage Source: https://prometheus.github.io/client_python/instrumenting/histogram Initialize a histogram and record an observation. ```python from prometheus_client import Histogram h = Histogram('request_latency_seconds', 'Description of histogram') h.observe(4.7) # Observe 4.7 (seconds in this case) ``` -------------------------------- ### make_wsgi_app Source: https://prometheus.github.io/client_python/exporting/http/wsgi Creates a WSGI application that serves Prometheus metrics. This can be integrated into existing WSGI servers. ```APIDOC ## make_wsgi_app(disable_compression=False) ### Description Creates a WSGI application to serve Prometheus metrics. By default, it supports Gzip compression if requested by the client. ### Parameters - **disable_compression** (bool) - Optional - If set to True, disables Gzip compression for the response. ### Example ```python from prometheus_client import make_wsgi_app from wsgiref.simple_server import make_server app = make_wsgi_app(disable_compression=True) httpd = make_server('', 8000, app) httpd.serve_forever() ``` ``` -------------------------------- ### CollectorRegistry Constructor Source: https://prometheus.github.io/client_python/registry Initializes a new CollectorRegistry instance. ```APIDOC ## CollectorRegistry(auto_describe=False, target_info=None, support_collectors_without_names=False) ### Description Creates a new registry instance to hold collectors. ### Parameters - **auto_describe** (bool) - Optional - If True, calls collect() on a collector at registration time if the collector does not implement describe(). - **target_info** (Dict[str, str]) - Optional - Key-value labels to attach as a target_info metric. - **support_collectors_without_names** (bool) - Optional - If True, allows registering collectors that produce no named metrics. ``` -------------------------------- ### Gauge(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, multiprocess_mode='all') Source: https://prometheus.github.io/client_python/instrumenting/gauge Constructor for creating a new Gauge metric instance. ```APIDOC ## Gauge Constructor ### Description Creates a new Gauge metric. The full metric name is formed by joining namespace, subsystem, and name with underscores. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text shown in the /metrics output. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Optional unit suffix. - **registry** (CollectorRegistry) - Optional - Registry to register with. - **multiprocess_mode** (str) - Optional - How to aggregate this gauge across multiple processes. ``` -------------------------------- ### Compressing push requests Source: https://prometheus.github.io/client_python/exporting/pushgateway Use the compression argument to enable gzip or snappy compression for network-constrained environments. ```python push_to_gateway( 'localhost:9091', job='batchA', registry=registry, handler=my_auth_handler, compression='gzip', ) ``` -------------------------------- ### Enable Exemplar Storage in Prometheus Source: https://prometheus.github.io/client_python/instrumenting/exemplars Required feature flag to enable exemplar storage in the Prometheus server. ```bash --enable-feature=exemplar-storage ``` -------------------------------- ### Basic FastAPI Prometheus Integration Source: https://prometheus.github.io/client_python/exporting/http/fastapi-gunicorn Mounts the Prometheus ASGI application to the /metrics endpoint of a FastAPI app. ```python from fastapi import FastAPI from prometheus_client import make_asgi_app # Create app app = FastAPI(debug=False) # Add prometheus asgi middleware to route /metrics requests metrics_app = make_asgi_app() app.mount("/metrics", metrics_app) ``` -------------------------------- ### GraphiteBridge(address, tags=False) Source: https://prometheus.github.io/client_python/bridges/graphite Initializes a bridge to push metrics to a Graphite server. ```APIDOC ## GraphiteBridge(address, tags=False) ### Description Initializes the bridge to connect to a Graphite server. Metrics can be pushed manually or via a background thread. ### Parameters - **address** (tuple) - Required - A tuple containing the hostname and port of the Graphite server (e.g., ('graphite.your.org', 2003)). - **tags** (bool) - Optional - Enable Graphite tags support. Defaults to False. ### Methods - **push()**: Pushes metrics to the Graphite server once. - **start(interval)**: Starts a daemon thread to push metrics every `interval` seconds. ``` -------------------------------- ### Expose Metrics in Multiprocess Mode Source: https://prometheus.github.io/client_python/multiprocess Initialize a CollectorRegistry with support_collectors_without_names=True and use MultiProcessCollector to aggregate metrics. ```python from prometheus_client import multiprocess from prometheus_client import generate_latest, CollectorRegistry, CONTENT_TYPE_LATEST, Counter MY_COUNTER = Counter('my_counter', 'Description of my counter') # Expose metrics. def app(environ, start_response): registry = CollectorRegistry(support_collectors_without_names=True) multiprocess.MultiProcessCollector(registry) data = generate_latest(registry) status = '200 OK' response_headers = [ ('Content-type', CONTENT_TYPE_LATEST), ('Content-Length', str(len(data))) ] start_response(status, response_headers) return iter([data]) ``` -------------------------------- ### Counter(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) Source: https://prometheus.github.io/client_python/instrumenting/counter Constructor for creating a new Counter metric instance. ```APIDOC ## Counter Constructor ### Description Creates a new Counter metric. A `_total` suffix is automatically appended to the metric name when exposed. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text for the metric. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Optional unit suffix. - **registry** (CollectorRegistry) - Optional - Registry to register with. ``` -------------------------------- ### Set target info labels Source: https://prometheus.github.io/client_python/registry Configures metadata labels exposed as a target_info metric. ```python REGISTRY.set_target_info({'env': 'production', 'region': 'us-east-1'}) ``` -------------------------------- ### Enum(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, states=[]) Source: https://prometheus.github.io/client_python/instrumenting/enum Constructor for creating a new Enum metric instance. ```APIDOC ## Enum Constructor ### Description Creates a new Enum metric to track a fixed set of states. The first state in the list is the default. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text shown in the /metrics output. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Not supported; raises ValueError. - **registry** (CollectorRegistry) - Optional - Registry to register with. - **states** (List[str]) - Required - The complete list of valid states. ``` -------------------------------- ### Skip global registration Source: https://prometheus.github.io/client_python/registry Demonstrates how to avoid registering metrics with the global registry. ```python from prometheus_client import Counter, CollectorRegistry # skip global registration — useful in tests c = Counter('my_counter', 'A counter', registry=None) # register with a custom registry r = CollectorRegistry() c2 = Counter('my_counter', 'A counter', registry=r) ``` -------------------------------- ### Initialize label values Source: https://prometheus.github.io/client_python/instrumenting/labels Pre-initialize label values by calling the .labels() method without incrementing. ```python from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/') c.labels('post', '/submit') ``` -------------------------------- ### Record Observations with observe() Source: https://prometheus.github.io/client_python/instrumenting/summary Record numerical values into the summary. ```python s.observe(0.43) # observe 430ms s.observe(1024) # observe 1024 bytes ``` -------------------------------- ### Expose metrics using MetricsResource in Twisted Source: https://prometheus.github.io/client_python/exporting/http/twisted Integrates Prometheus metrics into a Twisted web server by attaching MetricsResource to a resource tree. ```python from prometheus_client.twisted import MetricsResource from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet import reactor root = Resource() root.putChild(b'metrics', MetricsResource()) factory = Site(root) reactor.listenTCP(8000, factory) reactor.run() ``` -------------------------------- ### Increment Counter with amounts and exemplars Source: https://prometheus.github.io/client_python/instrumenting/counter Methods for incrementing the counter by specific amounts or attaching trace context via exemplars. ```python c.inc() # increment by 1 c.inc(5) # increment by 5 c.inc(0.7) # fractional increments are allowed ``` ```python c.inc(exemplar={'trace_id': 'abc123'}) ``` -------------------------------- ### Configuring TLS authentication Source: https://prometheus.github.io/client_python/exporting/pushgateway Implement a custom handler using tls_auth_handler to provide client certificates for secure communication. ```python from prometheus_client import CollectorRegistry, Gauge, push_to_gateway from prometheus_client.exposition import tls_auth_handler def my_auth_handler(url, method, timeout, headers, data): certfile = 'client-crt.pem' keyfile = 'client-key.pem' return tls_auth_handler(url, method, timeout, headers, data, certfile, keyfile) 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, handler=my_auth_handler) ``` -------------------------------- ### Collect metrics from registry Source: https://prometheus.github.io/client_python/registry Iterates through all metrics yielded by the registry. ```python for metric in REGISTRY.collect(): print(metric.name, metric.type) ``` -------------------------------- ### write_to_textfile(path, registry, escaping='allow-utf-8', tmpdir=None) Source: https://prometheus.github.io/client_python/exporting/textfile Writes metrics from a registry to a file in Prometheus text format atomically. ```APIDOC ## write_to_textfile(path, registry, escaping='allow-utf-8', tmpdir=None) ### Description Writes metrics from the registry to a file in Prometheus text format. The file is written atomically by writing to a temporary file first and then renaming it, preventing the Node exporter from reading a partially written file. ### Parameters - **path** (str) - Required - Destination file path. Must end in .prom for the Node exporter textfile collector to process it. - **registry** (Collector) - Required - Registry whose metrics are written. - **escaping** (str) - Optional (Default: 'allow-utf-8') - Escaping scheme for metric and label names. Accepted values: 'allow-utf-8', 'underscores', 'dots', 'values'. - **tmpdir** (Optional[str]) - Optional (Default: None) - Directory for the temporary file used during the atomic write. Defaults to the same directory as path. ### Returns - **None** - Raises an exception if the file cannot be written. ``` -------------------------------- ### Add Exemplars to Counter Metrics Source: https://prometheus.github.io/client_python/instrumenting/exemplars Attach exemplars to counter increments using a dictionary of label-value pairs. ```python from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc(exemplar={'trace_id': 'abc123'}) c.labels('post', '/submit').inc(1.0, {'trace_id': 'def456'}) ``` -------------------------------- ### Expose metrics in AIOHTTP Source: https://prometheus.github.io/client_python/exporting/http/aiohttp Use make_aiohttp_handler to create a metrics endpoint for an AIOHTTP application. ```python from aiohttp import web from prometheus_client.aiohttp import make_aiohttp_handler app = web.Application() app.router.add_get("/metrics", make_aiohttp_handler()) ``` -------------------------------- ### Configure Flask with Prometheus Middleware Source: https://prometheus.github.io/client_python/exporting/http/flask Uses DispatcherMiddleware to route /metrics requests to the Prometheus WSGI application. ```python from flask import Flask from werkzeug.middleware.dispatcher import DispatcherMiddleware from prometheus_client import make_wsgi_app # Create my app app = Flask(__name__) # Add prometheus wsgi middleware to route /metrics requests app.wsgi_app = DispatcherMiddleware(app.wsgi_app, { '/metrics': make_wsgi_app() }) ``` -------------------------------- ### ProcessCollector Source: https://prometheus.github.io/client_python/collector Initializes a collector that gathers process metrics from the /proc filesystem. This collector is only available on Linux systems. ```APIDOC ## ProcessCollector(namespace='', pid=lambda: 'self', proc='/proc', registry=REGISTRY) ### Description Collects process metrics from /proc. Only available on Linux. ### Parameters - **namespace** (str) - Optional - Prefix added to all metric names, e.g. 'mydaemon' produces mydaemon_process_cpu_seconds_total. - **pid** (Callable[[], int or str]) - Optional - Callable that returns the PID to monitor. 'self' monitors the current process. - **proc** (str) - Optional - Path to the proc filesystem. Useful for testing or containerised environments with a non-standard mount point. - **registry** (CollectorRegistry) - Optional - Registry to register with. Pass None to skip registration. ``` -------------------------------- ### Pushing metrics with Graphite tags Source: https://prometheus.github.io/client_python/bridges/graphite Enables Graphite tag support by setting the tags parameter to True during bridge initialization. ```python from prometheus_client.bridge.graphite import GraphiteBridge gb = GraphiteBridge(('graphite.your.org', 2003), tags=True) c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() gb.push() ``` -------------------------------- ### Info Metric Constructor Source: https://prometheus.github.io/client_python/instrumenting/info Signature for the Info class constructor. ```python Info(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) ``` -------------------------------- ### Pushing metrics to Graphite Source: https://prometheus.github.io/client_python/bridges/graphite Initializes the GraphiteBridge and pushes metrics either once or periodically in a daemon thread. ```python from prometheus_client.bridge.graphite import GraphiteBridge gb = GraphiteBridge(('graphite.your.org', 2003)) # Push once. gb.push() # Push every 10 seconds in a daemon thread. gb.start(10.0) ``` -------------------------------- ### Push metrics with HTTP Basic Authentication Source: https://prometheus.github.io/client_python/exporting/pushgateway Configures a custom handler to inject Authorization headers when connecting to a protected Pushgateway. ```python from prometheus_client import CollectorRegistry, Gauge, push_to_gateway from prometheus_client.exposition import basic_auth_handler def my_auth_handler(url, method, timeout, headers, data): username = 'foobar' password = 'secret123' return basic_auth_handler(url, method, timeout, headers, data, username, password) 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, handler=my_auth_handler) ``` -------------------------------- ### Define and increment labeled metrics with keyword arguments Source: https://prometheus.github.io/client_python/instrumenting/labels Labels can be passed as keyword arguments for better readability. ```python from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(method='get', endpoint='/').inc() c.labels(method='post', endpoint='/submit').inc() ``` -------------------------------- ### Observing Values Source: https://prometheus.github.io/client_python/instrumenting/histogram Record observations with or without exemplar trace context. ```python h.observe(0.43) # observe 430ms ``` ```python h.observe(0.43, exemplar={'trace_id': 'abc123'}) ``` -------------------------------- ### Proxying metrics with a custom Collector Source: https://prometheus.github.io/client_python/collector/custom Implements a custom collector to expose queue statistics as Gauge and Counter metrics. Requires registering the collector instance with the global REGISTRY. ```python from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily, REGISTRY from prometheus_client.registry import Collector from prometheus_client import start_http_server # Simulated external data source _QUEUE_STATS = { 'orders': {'depth': 14, 'processed': 9821}, 'notifications': {'depth': 3, 'processed': 45210}, } class QueueCollector(Collector): def collect(self): depth = GaugeMetricFamily( 'queue_depth', 'Current number of messages waiting in the queue', labels=['queue'], ) processed = CounterMetricFamily( 'queue_messages_processed_total', 'Total messages processed from the queue', labels=['queue'], ) for name, stats in _QUEUE_STATS.items(): depth.add_metric([name], stats['depth']) processed.add_metric([name], stats['processed']) yield depth yield processed REGISTRY.register(QueueCollector()) if __name__ == '__main__': start_http_server(8000) import time while True: time.sleep(1) ``` -------------------------------- ### Gauge Constructor Source: https://prometheus.github.io/client_python/instrumenting/gauge Signature for the Gauge constructor. ```python Gauge(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, multiprocess_mode='all') ``` -------------------------------- ### info(val) Source: https://prometheus.github.io/client_python/instrumenting/info Method to set the key-value pairs for the Info metric. ```APIDOC ## Method: info(val) ### Description Sets the key-value pairs for this metric. Calling this method overwrites any previous values. ### Parameters - **val** (dict[str, str]) - Required - A dictionary of string keys and values representing the metadata. ``` -------------------------------- ### PlatformCollector Source: https://prometheus.github.io/client_python/collector Initializes a collector that exports Python runtime metadata as a python_info gauge metric. ```APIDOC ## PlatformCollector(registry=REGISTRY, platform=None) ### Description Exports Python runtime metadata as a python_info gauge metric with labels. ### Parameters - **registry** (CollectorRegistry) - Optional - Registry to register with. Pass None to skip registration. - **platform** (module) - Optional - Override the platform module. Intended for testing. ``` -------------------------------- ### Initialize MultiProcessCollector Source: https://prometheus.github.io/client_python/multiprocess Registers a collector to aggregate metrics from the multiprocess directory. Ensure the registry is created within the request context to avoid duplicates. ```python from prometheus_client import multiprocess, CollectorRegistry def app(environ, start_response): registry = CollectorRegistry(support_collectors_without_names=True) multiprocess.MultiProcessCollector(registry) ... ``` ```python collector = multiprocess.MultiProcessCollector(registry, path='/var/run/prom') ``` -------------------------------- ### MultiProcessCollector(registry, path=None) Source: https://prometheus.github.io/client_python/multiprocess Initializes a collector that aggregates metrics written by all processes in the specified multiprocess directory. ```APIDOC ## MultiProcessCollector(registry, path=None) ### Description Collector that aggregates metrics written by all processes in the multiprocess directory. ### Parameters - **registry** (CollectorRegistry) - Required - Registry to register with. - **path** (Optional[str]) - Optional - Path to the directory containing the per-process metric files. Defaults to the PROMETHEUS_MULTIPROC_DIR environment variable. ### Exceptions - **ValueError**: Raised if path is not set or does not point to an existing directory. ``` -------------------------------- ### Basic Gauge Usage Source: https://prometheus.github.io/client_python/instrumenting/gauge Initialize a Gauge and perform basic increment, decrement, and set operations. ```python from prometheus_client import Gauge g = Gauge('my_inprogress_requests', 'Description of gauge') g.inc() # Increment by 1 g.dec(10) # Decrement by given value g.set(4.2) # Set to a given value ``` -------------------------------- ### Timing Code Execution Source: https://prometheus.github.io/client_python/instrumenting/histogram Use the time() method as a decorator or context manager to track duration. ```python @h.time() def process(): pass with h.time(): pass with h.time() as t: pass print(t.duration) # observed time in seconds. ``` -------------------------------- ### instance_ip_grouping_key Source: https://prometheus.github.io/client_python/exporting/pushgateway Returns a grouping key dict with the instance label set to the IP address of the current host. ```APIDOC ## instance_ip_grouping_key() ### Description Returns a grouping key dict with the instance label set to the IP address of the current host. Takes no parameters. ``` -------------------------------- ### make_aiohttp_handler Source: https://prometheus.github.io/client_python/exporting/http/aiohttp Creates a handler for AIOHTTP to serve Prometheus metrics. It supports optional response compression. ```APIDOC ## make_aiohttp_handler ### Description Creates a handler to be used with AIOHTTP routes to expose Prometheus metrics. ### Parameters - **disable_compression** (bool) - Optional - If set to True, disables automatic response compression for the metrics endpoint. ### Usage Example ```python from aiohttp import web from prometheus_client.aiohttp import make_aiohttp_handler app = web.Application() # Register the metrics handler app.router.add_get("/metrics", make_aiohttp_handler()) # Example with compression disabled app.router.add_get("/metrics", make_aiohttp_handler(disable_compression=True)) ``` ``` -------------------------------- ### Updating Info Metric Values Source: https://prometheus.github.io/client_python/instrumenting/info Use the info() method to set or overwrite key-value pairs for the metric. ```python i.info({'version': '1.4.2', 'revision': 'abc123', 'branch': 'main'}) ``` -------------------------------- ### Histogram Constructor Source: https://prometheus.github.io/client_python/instrumenting/histogram Initializes a new Histogram metric. The full metric name is formed by joining namespace, subsystem, and name with underscores. ```APIDOC ## Histogram(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, buckets=DEFAULT_BUCKETS) ### Description Creates a new Histogram instance to track distributions. ### Parameters - **name** (str) - Required - Metric name. - **documentation** (str) - Required - Help text shown in the /metrics output. - **labelnames** (Iterable[str]) - Optional - Names of labels for this metric. - **namespace** (str) - Optional - Optional prefix. - **subsystem** (str) - Optional - Optional middle component. - **unit** (str) - Optional - Optional unit suffix. - **registry** (CollectorRegistry) - Optional - Registry to register with. - **buckets** (Sequence[float]) - Optional - Upper bounds of the histogram buckets. ``` -------------------------------- ### Initialize and set Enum state Source: https://prometheus.github.io/client_python/instrumenting/enum Basic usage of the Enum class to define states and update the current state. ```python from prometheus_client import Enum e = Enum('my_task_state', 'Description of enum', states=['starting', 'running', 'stopped']) e.state('running') ``` -------------------------------- ### Push metrics to the Pushgateway Source: https://prometheus.github.io/client_python/exporting/pushgateway Uses a custom CollectorRegistry to push metrics to a specified Pushgateway instance. ```python 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) ``` -------------------------------- ### register(collector) Source: https://prometheus.github.io/client_python/registry Registers a collector with the registry. ```APIDOC ## register(collector) ### Description Register a collector with this registry. Raises ValueError if any of the metric names the collector produces are already registered. ``` -------------------------------- ### Histogram Constructor Signature Source: https://prometheus.github.io/client_python/instrumenting/histogram The signature for creating a new Histogram instance. ```python Histogram(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, buckets=DEFAULT_BUCKETS) ``` -------------------------------- ### get_target_info() Source: https://prometheus.github.io/client_python/registry Returns current target info labels. ```APIDOC ## get_target_info() ### Description Return the current target info labels as a Dict[str, str], or None if not set. ``` -------------------------------- ### Initialize and increment a Counter Source: https://prometheus.github.io/client_python/instrumenting/counter Basic usage of the Counter class to track values that only go up. ```python from prometheus_client import Counter c = Counter('my_failures', 'Description of counter') c.inc() # Increment by 1 c.inc(1.6) # Increment by given value ``` -------------------------------- ### basic_auth_handler Source: https://prometheus.github.io/client_python/exporting/pushgateway Wraps the default HTTP handler to include HTTP Basic Authentication headers. ```APIDOC ## basic_auth_handler(url, method, timeout, headers, data, username=None, password=None) ### Description Wraps the default handler and adds an HTTP Basic Auth header to the request. ### Parameters - **url** (str) - Required - Full request URL - **method** (str) - Required - HTTP method (PUT, POST, DELETE) - **timeout** (Optional[float]) - Required - Seconds before aborting - **headers** (List[Tuple[str, str]]) - Required - HTTP headers to include - **data** (bytes) - Required - Request body - **username** (Optional[str]) - Optional - HTTP Basic Auth username - **password** (Optional[str]) - Optional - HTTP Basic Auth password ``` -------------------------------- ### collect() Source: https://prometheus.github.io/client_python/registry Yields all metrics from every registered collector. ```APIDOC ## collect() ### Description Yield all metrics from every registered collector. Also yields the target_info metric if one has been set. ``` -------------------------------- ### Tracking In-Progress Operations Source: https://prometheus.github.io/client_python/instrumenting/gauge Use as a decorator or context manager to track active operations. ```python @g.track_inprogress() def process_job(): pass with g.track_inprogress(): pass ``` -------------------------------- ### observe(amount) Source: https://prometheus.github.io/client_python/instrumenting/summary Records a single observation for the summary. ```APIDOC ## observe(amount) ### Description Records a single observation. The amount is typically positive or zero. ### Parameters - **amount** (float/int) - Required - The value to observe. ``` -------------------------------- ### GCCollector Source: https://prometheus.github.io/client_python/collector Initializes a collector that exports Python garbage collector statistics. This is only active on CPython. ```APIDOC ## GCCollector(registry=REGISTRY) ### Description Exports Python garbage collector statistics. Only active on CPython (skipped silently on other implementations). ### Parameters - **registry** (CollectorRegistry) - Optional - Registry to register with. ``` -------------------------------- ### Configure ProcessCollector for a custom PID Source: https://prometheus.github.io/client_python/collector Use a lambda function to provide a dynamic PID for monitoring specific processes. ```python ProcessCollector(namespace='mydaemon', pid=lambda: open('/var/run/daemon.pid').read()) ``` -------------------------------- ### Enum constructor signature Source: https://prometheus.github.io/client_python/instrumenting/enum The constructor parameters for defining an Enum metric. ```python Enum(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, states=[]) ``` -------------------------------- ### set_target_info(labels) Source: https://prometheus.github.io/client_python/registry Sets or replaces target metadata labels. ```APIDOC ## set_target_info(labels) ### Description Set or replace the target metadata labels exposed as a target_info metric. Pass None to remove the target info metric. ```