Create custom metrics with the Info object
masterTo create a custom metric, define a function that returns a closure. The outer function handles persistent elements (like the prometheus_client metric instance), and the inner closure performs the actual instrumentation using the provided Info object.
The Info object contains:
request: The raw FastAPI request object.response: The FastAPI response object (can beNoneif an error occurred).handler: The matched route template.status: The (potentially grouped) status code.duration: The request duration.
Warning: Errors thrown in the handler are not caught by the instrumentator. Always check if the response is None before accessing it.
from typing import Callable
from prometheus_fastapi_instrumentator.metrics import Info
from prometheus_client import Counter
def http_requested_languages_total() -> Callable[[Info], None]:
# Persistent metric instance
METRIC = Counter(
"http_requested_languages_total",
"Number of times a certain language has been requested.",
labelnames=("langs",)
)
# The instrumentation closure
def instrumentation(info: Info) -> None:
langs = set()
lang_str = info.request.headers.get("Accept-Language", "")
for element in lang_str.split(","):
element = element.split(";")[0].strip().lower()
if element:
langs.add(element)
for language in langs:
METRIC.labels(language).inc()
return instrumentation
# Usage:
instrumentator.add(http_requested_languages_total())