aioprometheus.asgi.middleware module

class aioprometheus.asgi.middleware.MetricsMiddleware(app: Callable[[Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]], Awaitable[None]], registry: aioprometheus.collectors.Registry = <aioprometheus.collectors.Registry object>, exclude_paths: Sequence[str] = ('/metrics', '/metrics/', '/docs', '/openapi.json', '/docs/oauth2-redirect', '/redoc', '/favicon.ico'), use_template_urls: bool = True, group_status_codes: bool = False)

Bases: object

This class implements a Prometheus metrics collection middleware for ASGI applications.

The default metrics provided by this middleware include counters for requests received, responses sent, exceptions raised and status codes for route handlers.

Parameters
  • app – An ASGI callable. This callable represents the next ASGI callable in the chain which might be the application or another middleware.

  • registry – A collector registry to use when rendering metrics. If not specified then the default registry will be used.

  • exclude_paths – A list of urls that should not trigger updates to the default metrics.

  • use_template_urls – A boolean that defines whether route template URLs should be used by the default route monitoring metrics. Template URLs will report ‘/users/{user_id}’ instead of ‘/users/bob’ or ‘/users/alice’, etc. The template URLS can be more useful than the actual route url as they allow the route handler to be easily identified. This feature is only supported with Starlette / FastAPI currently.

  • group_status_codes – A boolean that defines whether status codes should be grouped under a value representing that code kind. For example, 200, 201, etc will all be grouped under 2xx. The default value is False which means that status codes are not grouped.

get_full_or_template_path(scope) str

Using the route template url can be more insightful than the actual route url so that the route handler function can be easily identified.

For example, seeing the path ‘/users/{user_id}’ in metrics is often better than every combination of ‘/users/bob’, /users/alice’, etc.

Obtaining the route template will be a unique procedure for each web framework. This feature is currently only supported for Starlette and FastAPI applications.