feat: let admins exclude routes like health checks from OpenTelemetry metrics (#33329)

With OpenTelemetry metrics on, every request is counted in the HTTP request and duration metrics, so Kubernetes liveness and readiness probes on `/health` and `/health/db` fill the time series database and dashboards with noise. These metrics now skip any request whose URL matches `OTEL_PYTHON_FASTAPI_EXCLUDED_URLS` (or `OTEL_PYTHON_EXCLUDED_URLS` as a fallback), the standard OpenTelemetry variable that traces already honour. It takes a comma-separated list of regular expressions such as `/health,/_app/immutable/.*`, each matched anywhere in the URL, so `/health` also covers `/health/db`. One pattern now drops the same requests from traces and metrics alike. Nothing changes when the variable is unset.

Closes #31609
This commit is contained in:
Classic298 2026-10-28 22:21:06 +02:00 • committed by GitHub
parent 34ef99dbfb
commit 76b7be67fc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -41,12 +41,14 @@ from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
OTLPMetricExporter as OTLPHttpMetricExporter,
)
from opentelemetry.instrumentation.asgi import get_host_port_url_tuple
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
PeriodicExportingMetricReader,
)
from opentelemetry.sdk.metrics.view import View
from opentelemetry.sdk.resources import Resource
from opentelemetry.util.http import get_excluded_urls
from sqlalchemy import Engine, func, select
from sqlalchemy.orm import Session
@ -222,9 +224,16 @@ def setup_metrics(app: FastAPI, resource: Resource, db_engine: Engine) -> None:
callbacks=[observe_users_active_today],
)
# OTEL_PYTHON_FASTAPI_EXCLUDED_URLS, shared with traces
excluded_urls = get_excluded_urls('FASTAPI')
# FastAPI middleware
@app.middleware('http')
async def _metrics_middleware(request: Request, call_next):
_, _, url = get_host_port_url_tuple(request.scope)
if excluded_urls.url_disabled(url):
return await call_next(request)
start_time = time.perf_counter()
status_code = None