### Real-world example Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md An example demonstrating how to track the duration of background tasks using the Summary metric, including starting an HTTP server to expose metrics. ```APIDOC ## Real-world example Tracking the duration of 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 ... ``` This produces: ``` myapp_task_duration_seconds_count{task_type="email"} 120 myapp_task_duration_seconds_sum{task_type="email"} 48.3 ``` You can compute the average duration in PromQL as: ``` rate(myapp_task_duration_seconds_sum[5m]) / rate(myapp_task_duration_seconds_count[5m]) ``` ``` -------------------------------- ### Real-world Example: Tracking DB Connections and Queue Size Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md A practical example demonstrating the use of Gauges to track active database connections and the size of a job queue. It includes setting a Gauge using a callback function and starting an HTTP server to expose metrics. ```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 ... ``` -------------------------------- ### Real-world example Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/histogram.md Example demonstrating how to track HTTP request latency using a Histogram with custom buckets and labels. ```APIDOC ## Real-world example Tracking HTTP request latency with custom buckets tuned to the workload: ```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 ... ``` This produces time series like: ``` 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 ``` ``` -------------------------------- ### Serve documentation locally Source: https://github.com/prometheus/client_python/blob/master/docs/README.md Starts a local Hugo development server to preview documentation changes. ```shell hugo server -D ``` -------------------------------- ### InfoMetricFamily Examples Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Examples demonstrating how to use InfoMetricFamily for both unlabelled and labelled metrics. ```APIDOC ## InfoMetricFamily Usage Examples ### Single unlabelled info metric: ```python yield InfoMetricFamily('build', 'Build metadata', value={'version': '1.2.3', 'commit': 'abc123'}) ``` ### Labelled — one info metric per service: ```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 ``` ``` -------------------------------- ### Install npm packages and build assets Source: https://github.com/prometheus/client_python/blob/master/docs/themes/hugo-geekdoc/README.md Install required packages and run the build script to create necessary assets for the theme. This is required if using the theme from a cloned branch instead of a release tarball. ```shell npm install ``` ```shell npm run build ``` ```shell npm run pack ``` -------------------------------- ### Install Prometheus Python Client Source: https://github.com/prometheus/client_python/blob/master/README.md Use pip to install the Prometheus Python client library. This package can be found on PyPI. ```bash pip install prometheus-client ``` -------------------------------- ### Real-world Example: Tracking Background Task Duration Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md A practical example of using Summary with labels to track the duration of background tasks and expose metrics via HTTP. ```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 ... ``` -------------------------------- ### Real-world Example: Tracking HTTP Requests and Exceptions Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md A comprehensive example showing how to use Counters for tracking HTTP requests and unhandled exceptions in a web application. ```APIDOC ## Real-world Example: Tracking HTTP Requests and Exceptions ### Description This example demonstrates a practical application of Counters for monitoring a web service, including tracking total requests by method and status, and counting unhandled exceptions per handler. ### Code Example ```python from prometheus_client import Counter, start_http_server import time # Counter for tracking total HTTP requests REQUESTS = Counter( 'requests_total', 'Total HTTP requests received', labelnames=['method', 'status'], namespace='myapp' ) # Counter for tracking unhandled exceptions EXCEPTIONS = Counter( 'exceptions_total', 'Total unhandled exceptions', labelnames=['handler'], namespace='myapp' ) def handle_request(method, handler): # Use count_exceptions as a context manager to track exceptions with EXCEPTIONS.labels(handler=handler).count_exceptions(): # Simulate request processing print(f"Handling request: {method} on {handler}") if handler == "error_handler": raise ValueError("Simulated error") status = '200' # Assume success for now # Increment the requests counter after successful processing (or if exception is handled) REQUESTS.labels(method=method, status=status).inc() if __name__ == '__main__': # Start up the server to expose the metrics. In a real app, this would be run in a separate thread or process. start_http_server(8000) print("HTTP server started on port 8000. Metrics available at http://localhost:8000/metrics") # Simulate incoming requests try: handle_request('GET', 'home') handle_request('POST', 'submit') handle_request('GET', 'error_handler') # This will raise an exception except ValueError as e: print(f"Caught expected exception: {e}") # Keep the main thread alive to allow the server to run while True: time.sleep(1) ``` ### Explanation - `REQUESTS` counter tracks requests, labeled by HTTP method and status code. - `EXCEPTIONS` counter tracks unhandled exceptions, labeled by the handler function name. - The `count_exceptions` method is used as a context manager to automatically increment the `EXCEPTIONS` counter when an exception occurs within the `with` block. - The `REQUESTS` counter is incremented after the request handling logic, assuming a status code (in a real app, this would be determined by the response). - `start_http_server(8000)` exposes the metrics at `http://localhost:8000/metrics`. ### Output Example (at `http://localhost:8000/metrics`) ``` # HELP myapp_requests_total Total HTTP requests received # TYPE myapp_requests_total counter myapp_requests_total{method= ``` ```APIDOC GET",status="200"} 1.0 # HELP myapp_exceptions_total Total unhandled exceptions # TYPE myapp_exceptions_total counter myapp_exceptions_total{handler="error_handler"} 1.0 ``` -------------------------------- ### Start HTTPS Server Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/_index.md Enables HTTPS by providing certificate and key files. This is necessary for secure metric exposition. ```python from prometheus_client import start_http_server start_http_server(8000, certfile="server.crt", keyfile="server.key") ``` -------------------------------- ### Start HTTP Server Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/_index.md Starts an HTTP server on the specified port in a daemon thread. Visit http://localhost:8000/ to view metrics. ```python from prometheus_client import start_http_server start_http_server(8000) ``` -------------------------------- ### Expose application build metadata Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/info.md A complete example showing how to define an Info metric and expose it 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 Counter Implementation Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Full example of tracking HTTP requests and exceptions in a web application. ```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 ... ``` -------------------------------- ### Custom Collector Example Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md A real-world example of creating a custom collector by subclassing `Collector` and implementing the `collect` method to expose metrics from an external data source. ```APIDOC ## Custom Collector Implementation ### Description This example shows how to create a custom collector `QueueCollector` that gathers metrics from a simulated external data source `_QUEUE_STATS` and registers it with the Prometheus registry. ### Code Example ```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) ``` ``` -------------------------------- ### Construct Metric with Namespace and Subsystem Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Example of how namespace, subsystem, and name parameters are combined to form 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') ``` -------------------------------- ### Real-world HTTP Request Latency Tracking Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/histogram.md Example of tracking HTTP request latency with custom buckets and labels for method and endpoint. It starts an HTTP server to expose metrics. ```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 ... ``` -------------------------------- ### Run Flask App with uWSGI Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/flask.md This bash command installs uWSGI and then runs the Flask application defined in `myapp.py`, making it accessible at http://127.0.0.1:8000. Visit http://localhost:8000/metrics to view the exposed metrics. ```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 ``` -------------------------------- ### Run FastAPI with Gunicorn Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/fastapi-gunicorn.md Command to start the application using the Uvicorn worker class. ```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 ``` -------------------------------- ### Start a WSGI server in a new thread Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/wsgi.md Use start_wsgi_server to serve metrics through the WSGI reference implementation in a background thread. ```python from prometheus_client import start_wsgi_server start_wsgi_server(8000) ``` -------------------------------- ### Push Metrics to Graphite Source: https://github.com/prometheus/client_python/blob/master/docs/content/bridges/graphite.md Instantiate GraphiteBridge and push metrics. Use start() to push 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) ``` -------------------------------- ### Initialize MultiProcessCollector and Expose Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/multiprocess/_index.md Initialize a CollectorRegistry with support for collectors without names and add a MultiProcessCollector. This setup is recommended within a request context to avoid duplicate metrics. Metrics are then generated and exposed. ```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]) ``` -------------------------------- ### GaugeMetricFamily Constructor and add_metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Documentation for the `GaugeMetricFamily` constructor and its `add_metric` method, including parameter details and usage examples. ```APIDOC ## GaugeMetricFamily ### Description Represents a Gauge metric family. Can be used to emit single unlabelled metrics or labelled metrics. ### Constructor `GaugeMetricFamily(name, documentation, value=None, labels=None, unit='')` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `name` | `str` | required | Metric name. | | `documentation` | `str` | required | Help text shown in the `/metrics` output. | | `value` | `float` | `None` | Emit a single unlabelled sample with this value. Mutually exclusive with `labels`. | | `labels` | `Sequence[str]` | `None` | Label names. Use with `add_metric`. Mutually exclusive with `value`. | | `unit` | `str` | `''` | Optional unit suffix appended to the metric name. | ### `add_metric(labels, value, timestamp=None)` Add a labelled sample to the metric family. | Parameter | Type | Description | |-----------|------|-------------| | `labels` | `Sequence[str]` | Label values in the same order as the `labels` constructor argument. | | `value` | `float` | The gauge value. | | `timestamp` | `float` or `Timestamp` | Optional Unix timestamp for the sample. | ### Example ```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 ``` ``` -------------------------------- ### Track background worker lifecycle Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/enum.md A complete example demonstrating how to track the state of a background worker using an Enum metric. ```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 ... ``` -------------------------------- ### Create Flask App with Prometheus Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/flask.md This Python code sets up a basic Flask application and integrates the Prometheus WSGI middleware to expose metrics at the /metrics endpoint. Ensure `prometheus_client` and `Flask` are installed. ```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() }) ``` -------------------------------- ### GCCollector Initialization Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/_index.md Example of initializing GCCollector, which exports Python garbage collector statistics. This collector is only active on CPython. ```python GCCollector(registry=REGISTRY) ``` -------------------------------- ### Get Target Info Labels Source: https://github.com/prometheus/client_python/blob/master/docs/content/registry/_index.md Retrieves the current target info labels as a dictionary, or `None` if not set. ```python info = REGISTRY.get_target_info() ``` -------------------------------- ### Define Enum with namespace and subsystem Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/enum.md Example of how namespace, subsystem, and name parameters combine to form the full 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') ``` -------------------------------- ### Implement a Custom Collector Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Create a custom collector by inheriting from `Collector` and implementing the `collect` method. This example demonstrates yielding `GaugeMetricFamily` and `CounterMetricFamily` objects. Register the custom collector with the default registry. ```python from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY from prometheus_client.registry import Collector class CustomCollector(Collector): def collect(self): yield GaugeMetricFamily('my_gauge', 'Help text', value=7) c = CounterMetricFamily('my_counter_total', 'Help text', labels=['foo']) c.add_metric(['bar'], 1.7) c.add_metric(['baz'], 3.8) yield c REGISTRY.register(CustomCollector()) ``` -------------------------------- ### Generated Metrics for Background Tasks Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Shows the resulting Prometheus metrics generated by the real-world example, including count and sum with labels. ```text myapp_task_duration_seconds_count{task_type="email"} 120 myapp_task_duration_seconds_sum{task_type="email"} 48.3 ``` -------------------------------- ### Instrument Python Application with Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/_index.md Use the prometheus-client library to track request processing time with a Summary metric and expose it via an HTTP server. Ensure the server is started before generating requests. ```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()) ``` -------------------------------- ### ProcessCollector with Custom Namespace and PID Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/_index.md Example of initializing ProcessCollector with a custom namespace and a PID callable. This allows monitoring of other processes by specifying their PID. ```python ProcessCollector(namespace='mydaemon', pid=lambda: open('/var/run/daemon.pid').read()) ``` -------------------------------- ### Get Sample Value for Unit Tests Source: https://github.com/prometheus/client_python/blob/master/docs/content/registry/_index.md Retrieves the current value of a single sample by name and optional labels. Intended for unit testing and not efficient for production use. ```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 ``` -------------------------------- ### CustomCollector Example Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md An example of a custom collector class that yields GaugeMetricFamily and CounterMetricFamily objects. ```APIDOC ## CustomCollector Example ### Description This example demonstrates how to create a custom collector by subclassing `Collector` and implementing the `collect` method to yield metric families. ### Code ```python from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY from prometheus_client.registry import Collector class CustomCollector(Collector): def collect(self): yield GaugeMetricFamily('my_gauge', 'Help text', value=7) c = CounterMetricFamily('my_counter_total', 'Help text', labels=['foo']) c.add_metric(['bar'], 1.7) c.add_metric(['baz'], 3.8) yield c REGISTRY.register(CustomCollector()) ``` ``` -------------------------------- ### Example restricted metrics output Source: https://github.com/prometheus/client_python/blob/master/docs/content/restricted-registry/_index.md The expected output format when querying restricted 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 ``` -------------------------------- ### Create Basic ASGI App Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/asgi.md Use `make_asgi_app` to create a default ASGI application for Prometheus metrics. This app handles compression by default. ```python from prometheus_client import make_asgi_app app = make_asgi_app() ``` -------------------------------- ### Create CounterMetricFamily with Labels Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Instantiate `CounterMetricFamily` with a name, documentation, and a list of label names. Use `add_metric` to add labelled samples with their cumulative values. This is suitable for metrics that only increase. ```python c = CounterMetricFamily('my_counter_total', 'Help text', labels=['foo']) c.add_metric(['bar'], 1.7) c.add_metric(['baz'], 3.8) yield c ``` -------------------------------- ### Counter Initialization and Usage Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Demonstrates how to initialize a Counter and increment its value. ```APIDOC ## Counter Initialization and Usage ### Description A Counter tracks a value that only ever goes up. It is suitable for metrics like requests served, errors raised, or bytes sent. The counter resets to zero when the process restarts. ### Constructor ```python Counter(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) ``` **Parameters**: - **name** (str) - Required - Metric name. A `_total` suffix is appended automatically when exposing the time series. - **documentation** (str) - Required - Help text shown in the `/metrics` output and Prometheus UI. - **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 appended to the metric name. - **registry** (CollectorRegistry) - Optional - Registry to register with. Pass `None` to skip registration. ### Methods #### `inc(amount=1, exemplar=None)` Increment the counter by the given amount. The amount must be non-negative. ```python c.inc() # increment by 1 c.inc(5) # increment by 5 c.inc(0.7) # fractional increments are allowed c.inc(exemplar={'trace_id': 'abc123'}) # with exemplar ``` #### `reset()` Reset the counter to zero. Use this when a logical process restarts without restarting the actual Python process. ```python c.reset() ``` #### `count_exceptions(exception=Exception)` Count exceptions raised in a block of code or function. Can be used as a decorator or context manager. ```python @c.count_exceptions() def f(): pass with c.count_exceptions(): pass with c.count_exceptions(ValueError): pass ``` ### Request Example ```python from prometheus_client import Counter c = Counter('my_failures', 'Description of counter') c.inc() c.inc(1.6) ``` ### Response Example (No direct response example for metric creation, but metrics are exposed via an HTTP endpoint, typically `/metrics`) ``` -------------------------------- ### Summary Constructor Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Instantiates a Summary metric. It requires a name and documentation string, and accepts optional parameters for labels, namespace, subsystem, unit, and registry. ```APIDOC ## Summary Constructor ```python Summary(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `name` | `str` | required | Metric name. | | `documentation` | `str` | required | Help text shown in the `/metrics` output and Prometheus UI. | | `labelnames` | `Iterable[str]` | `()` | Names of labels for this metric. See [Labels](../labels/). Note: `quantile` is reserved and cannot be used as a label name. | | `namespace` | `str` | `''` | Optional prefix. | | `subsystem` | `str` | `''` | Optional middle component. | | `unit` | `str` | `''` | Optional unit suffix appended to the metric name. | | `registry` | `CollectorRegistry` | `REGISTRY` | Registry to register with. Pass `None` to skip registration, which is useful in tests where you create metrics without wanting them in the global registry. | `namespace`, `subsystem`, and `name` are joined with underscores 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 and Observe Summary Metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Instantiate a Summary metric and record an observation. The amount observed is typically positive or zero. ```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) ``` -------------------------------- ### Summary Constructor Parameters Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Defines the parameters for creating a Summary metric, including name, documentation, labels, and optional namespace/subsystem/unit. ```python Summary(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) ``` -------------------------------- ### Define Info metric with namespace and subsystem Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/info.md Demonstrates how namespace and subsystem parameters are joined with the name to form the full metric name. ```python # namespace='myapp', subsystem='http', name='build' # produces: myapp_http_build_info Info('build', 'Build information', namespace='myapp', subsystem='http') ``` -------------------------------- ### Constructing Full Metric Name Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Illustrates how namespace, subsystem, and name are joined with underscores to form the complete 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') ``` -------------------------------- ### Initialize and set Info metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/info.md Basic usage for creating an Info metric and setting 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'}) ``` -------------------------------- ### Basic Gauge Usage Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md Demonstrates the basic instantiation and manipulation of a Gauge metric. Use this for tracking values that fluctuate over time. ```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 ``` -------------------------------- ### Query restricted metrics via HTTP Source: https://github.com/prometheus/client_python/blob/master/docs/content/restricted-registry/_index.md Use the name[] parameter in a GET request to filter metrics when using the built-in HTTP server. ```bash curl --get --data-urlencode "name[]=python_gc_objects_collected_total" --data-urlencode "name[]=python_info" http://127.0.0.1:9200/metrics ``` -------------------------------- ### Create a WSGI application for Prometheus Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/wsgi.md Use make_wsgi_app to create a WSGI application that can be served by a standard WSGI 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() ``` -------------------------------- ### Custom Collector for Queue Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Implements a custom Collector to expose queue depth and processed message counts as Prometheus metrics. This example demonstrates how to integrate external data into Prometheus. ```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) ``` -------------------------------- ### Create ASGI App with Compression Disabled Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/asgi.md Create an ASGI application for Prometheus metrics while explicitly disabling response compression by setting `disable_compression=True`. ```python app = make_asgi_app(disable_compression=True) ``` -------------------------------- ### Labelled Info Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Creates a labelled InfoMetricFamily and adds multiple metrics, each with specific service labels and build information. ```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 ``` -------------------------------- ### Tracking In-Progress Operations with Gauge Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md Provides examples of using the `track_inprogress` method as a decorator or context manager to automatically increment a Gauge upon entry and decrement upon exit of a code block or function. ```python @g.track_inprogress() def process_job(): pass with g.track_inprogress(): pass ``` -------------------------------- ### Initialize Histogram with Custom Buckets Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/histogram.md Initialize a Histogram with custom bucket boundaries. This allows tuning the histogram to specific workload characteristics. ```python h = Histogram('request_latency_seconds', 'Latency', buckets=[.1, .5, 1, 2, 5]) ``` -------------------------------- ### Observe Method Usage Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/summary.md Demonstrates recording single observations with the `observe` method, which accepts a numerical amount. ```python s.observe(0.43) # observe 430ms s.observe(1024) # observe 1024 bytes ``` -------------------------------- ### Get Featured Image Permalink Source: https://github.com/prometheus/client_python/blob/master/docs/themes/hugo-geekdoc/layouts/partials/utils/featured.html This Go template code snippet retrieves the permalink for a featured image, falling back to other image sources if necessary. It's used for generating image URLs in templates. ```go-html-template {{ $img := "" }} {{ with $source := ($.Resources.ByType "image").GetMatch "{\*feature\*,\*cover\*,\*thumbnail\*}" }} {{ $featured := .Fill (printf "1200x630 %s" (default "Smart" .Params.anchor)) }} {{ $img = $featured.Permalink }} {{ else }} {{ with default $.Site.Params.images $.Params.images }} {{ $img = index . 0 | absURL }} {{ end }} {{ end }} {{ return $img }} ``` -------------------------------- ### Create GaugeMetricFamily with Labels Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Instantiate `GaugeMetricFamily` with a name, documentation, and a list of label names. Then, use `add_metric` to add labelled samples with their corresponding values. This is useful for emitting multiple time series for a single metric. ```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 and Use CollectorRegistry Source: https://github.com/prometheus/client_python/blob/master/docs/content/registry/_index.md Demonstrates using the default global registry and creating an isolated registry for testing. Metric constructors automatically register with the default REGISTRY unless specified otherwise. ```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) ``` -------------------------------- ### Enable Exemplar Storage in Prometheus Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/exemplars.md Configuration flag required on the Prometheus server to enable the storage and retrieval of exemplars. This is necessary for viewing exemplar data within Prometheus. ```bash --enable-feature=exemplar-storage ``` -------------------------------- ### Observe Value with Exemplar Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/histogram.md Record a single observation with an exemplar. Exemplars attach trace context and are rendered in OpenMetrics format. ```python h.observe(0.43, exemplar={'trace_id': 'abc123'}) ``` -------------------------------- ### Using Labels with Prometheus Metrics Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/labels.md Demonstrates how to add labels to metrics like Counters and initialize them. ```APIDOC ## Using Labels with Prometheus Metrics ### Description Metrics can be enhanced with labels to group related time series. This section shows how to declare and use labels with a Counter metric. ### Method `Counter(name, documentation, labelnames)` ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from prometheus_client import Counter # Declaring a Counter with labels 'method' and 'endpoint' c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) # Incrementing with label values passed as positional arguments c.labels('get', '/').inc() c.labels('post', '/submit').inc() # Incrementing with label values passed as keyword arguments c.labels(method='get', endpoint='/').inc() c.labels(method='post', endpoint='/submit').inc() ``` ### Response N/A (Client-side operation) ## Initializing Label Values ### Description Metrics with labels are not initialized upon declaration. It's recommended to initialize label values by calling the `.labels()` method alone to ensure all possible label combinations are known. ### Method `metric.labels(*labelvalues)` or `metric.labels(**labelkwargs)` ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) # Initializing label sets c.labels('get', '/') c.labels('post', '/submit') ``` ### Response N/A (Client-side operation) ``` -------------------------------- ### CollectorRegistry Constructor Source: https://github.com/prometheus/client_python/blob/master/docs/content/registry/_index.md Initializes a new CollectorRegistry. Parameters control automatic description, target info, and support for collectors without names. ```APIDOC ## CollectorRegistry Constructor ### Description Initializes a new CollectorRegistry. ### Parameters #### Constructor Parameters - **auto_describe** (bool) - Optional - If `True`, calls `collect()` on a collector at registration time if the collector does not implement `describe()`. Used to detect duplicate metric names. The default `REGISTRY` is created with `auto_describe=True`. - **target_info** (Dict[str, str]) - Optional - Key-value labels to attach as a `target_info` metric. Equivalent to calling `set_target_info` after construction. - **support_collectors_without_names** (bool) - Optional - If `True`, allows registering collectors that produce no named metrics (i.e. whose `describe()` returns an empty list). ``` -------------------------------- ### Increment Counter with Amounts Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Demonstrates incrementing by default or specific values, including fractional amounts. ```python c.inc() # increment by 1 c.inc(5) # increment by 5 c.inc(0.7) # fractional increments are allowed ``` -------------------------------- ### Create GaugeMetricFamily with Value Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Instantiate `GaugeMetricFamily` with a name, documentation, and a direct `value`. This is used for emitting a single, unlabelled metric. ```python GaugeMetricFamily('my_gauge', 'Help text', value=7) ``` -------------------------------- ### Gauge Constructor with Namespace and Subsystem Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md Shows how to construct a Gauge metric with a specified namespace and subsystem to organize metric names. The full metric name is formed by joining these components with underscores. ```python # namespace='myapp', subsystem='db', name='connections_active' # produces: myapp_db_connections_active Gauge('connections_active', 'Active DB connections', namespace='myapp', subsystem='db') ``` -------------------------------- ### Expose metrics in FastAPI Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/http/fastapi-gunicorn.md Mounts the Prometheus ASGI application to the /metrics endpoint. ```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) ``` -------------------------------- ### Counter with Labels Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Illustrates how to use labels with the Counter metric for more granular tracking. ```APIDOC ## Counter with Labels ### Description Labels allow you to categorize and slice your time series data. For example, you can track HTTP requests by method and status code. ### Constructor with Labels ```python Counter(name, documentation, labelnames=['label1', 'label2'], ...) ``` ### Methods for Labels - `.labels(*labelvalues)`: Returns a new metric object with the given label values set. - `.remove(*labelvalues)`: Removes a time series with the given label values. - `.remove_by_labels(**labels)`: Removes time series matching the given label dictionary. - `.clear()`: Removes all time series for this metric. ### Request Example ```python from prometheus_client import Counter REQUESTS = Counter( 'requests_total', 'Total HTTP requests received', labelnames=['method', 'status'], namespace='myapp' ) # Incrementing with labels REQUESTS.labels(method='GET', status='200').inc() REQUESTS.labels(method='POST', status='404').inc(2) ``` ### Response Example (Metrics with labels are exposed via an HTTP endpoint, typically `/metrics`. The output would look like: ``` # HELP myapp_requests_total Total HTTP requests received # TYPE myapp_requests_total counter myapp_requests_total{method="GET",status="200"} 1.0 myapp_requests_total{method="POST",status="404"} 2.0 ``` ) ``` -------------------------------- ### GaugeMetricFamily Constructor and add_metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Demonstrates the constructor for `GaugeMetricFamily` and the `add_metric` method for adding labelled samples. This pattern is used within the `collect` method of a custom collector. ```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) ``` -------------------------------- ### Setting Gauge Value Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md Demonstrates how to set a Gauge metric to a specific numerical value. ```python g.set(42.5) ``` -------------------------------- ### Gauge Constructor Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/gauge.md Initializes a new Gauge metric. It accepts a name, documentation string, and optional parameters for labels, namespace, subsystem, unit, registry, and multiprocess mode. ```APIDOC ## Gauge Constructor ```python Gauge(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, multiprocess_mode='all') ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `name` | `str` | required | Metric name. | | `documentation` | `str` | required | Help text shown in the `/metrics` output and Prometheus UI. | | `labelnames` | `Iterable[str]` | `()` | Names of labels for this metric. See [Labels](../labels/). | | `namespace` | `str` | `''` | Optional prefix. | | `subsystem` | `str` | `''` | Optional middle component. | | `unit` | `str` | `''` | Optional unit suffix appended to the metric name. | | `registry` | `CollectorRegistry` | `REGISTRY` | Registry to register with. Pass `None` to skip registration, which is useful in tests where you create metrics without wanting them in the global registry. | | `multiprocess_mode` | `str` | `'all'` | How to aggregate this gauge across multiple processes. See [Multiprocess mode](../../multiprocess/). Options: `all`, `liveall`, `min`, `livemin`, `max`, `livemax`, `sum`, `livesum`, `mostrecent`, `livemostrecent`. | `namespace`, `subsystem`, and `name` are joined with underscores to form the full metric name: ```python # namespace='myapp', subsystem='db', name='connections_active' # produces: myapp_db_connections_active Gauge('connections_active', 'Active DB connections', namespace='myapp', subsystem='db') ``` ``` -------------------------------- ### CounterMetricFamily Constructor and add_metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Use CounterMetricFamily to create a counter metric. The '_total' suffix is automatically handled. Labels are used to differentiate metrics. ```python CounterMetricFamily(name, documentation, value=None, labels=None, created=None, unit='', exemplar=None) ``` ```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 ``` -------------------------------- ### Push Metrics to Pushgateway Source: https://github.com/prometheus/client_python/blob/master/docs/content/exporting/pushgateway.md Pushes metrics from a specific registry to the Pushgateway. A separate registry is recommended to avoid including default metrics. ```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) ``` -------------------------------- ### Initialize and Observe Histogram Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/histogram.md Initialize a Histogram metric and observe a single value. The value is typically a duration in seconds. ```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) ``` -------------------------------- ### Increment Counter with Exemplar Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/counter.md Attaching trace context to a counter increment using an exemplar dictionary. ```python c.inc(exemplar={'trace_id': 'abc123'}) ``` -------------------------------- ### SummaryMetricFamily Constructor and add_metric Source: https://github.com/prometheus/client_python/blob/master/docs/content/collector/custom.md Use SummaryMetricFamily to create a summary metric. Both count_value and sum_value must be provided together. Labels can be used to differentiate metrics. ```python SummaryMetricFamily(name, documentation, count_value=None, sum_value=None, labels=None, unit='') ``` ```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 ``` -------------------------------- ### Initializing Label Values Source: https://github.com/prometheus/client_python/blob/master/docs/content/instrumenting/labels.md 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') ```