Skip to content

# `metrics`

Here's the reference for the Prometheus metrics registry and endpoint handler.

You can import them directly from `fastapi_toolsets.metrics`:

    from fastapi_toolsets.metrics import Metric, MetricsRegistry, init_metrics

## `fastapi_toolsets.metrics.registry.Metric` `dataclass`

A metric definition with metadata.

## `fastapi_toolsets.metrics.registry.MetricsRegistry`

Registry for managing Prometheus metric providers and collectors.

### `get(name)`

Return the metric instance created by a provider.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`name` | `str` | The metric name (defaults to the provider function name). | required

Raises:

Type | Description
--- | ---
`KeyError` | If the metric name is unknown or `init_metrics` has not been called yet.

### `get_all()`

Get all registered metric definitions.

### `get_collectors()`

Get collectors (called on each scrape).

### `get_providers()`

Get metric providers (called once at init).

### `include_registry(registry)`

Include another :class:`MetricsRegistry` into this one.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`registry` | `MetricsRegistry` | The registry to merge in. | required

Raises:

Type | Description
--- | ---
`ValueError` | If a metric name already exists in the current registry.

### `register(func=None, *, name=None, collect=False)`

Register a metric provider or collector function.

Can be used as a decorator with or without arguments.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`func` | `Callable[..., Any] | None` | The metric function to register. | `None`
`name` | `str | None` | Metric name (defaults to function name). | `None`
`collect` | `bool` | If `True`, the function is called on every scrape. If `False` (default), called once at init time. | `False`

## `fastapi_toolsets.metrics.handler.init_metrics(app, registry, *, path='/metrics')`

Register a Prometheus `/metrics` endpoint on a FastAPI app.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`app` | `FastAPI` | FastAPI application instance. | required
`registry` | `MetricsRegistry` | A :class:`MetricsRegistry` containing providers and collectors. | required
`path` | `str` | URL path for the metrics endpoint (default `/metrics`). | `'/metrics'`

Returns:

Type | Description
--- | ---
`FastAPI` | The same FastAPI instance (for chaining).

Example

    from fastapi import FastAPI
    from fastapi_toolsets.metrics import MetricsRegistry, init_metrics

    metrics = MetricsRegistry()
    app = FastAPI()
    init_metrics(app, registry=metrics)