Repository navigation
Honor opentelemetry_exclude_urls in the Litestar bootstrapper - #151
Conversation
| from microbootstrap.config.faststream import FastStreamConfig | ||
| from microbootstrap.instruments.health_checks_instrument import HealthChecksInstrument | ||
| from microbootstrap.instruments.logging_instrument import LoggingInstrument | ||
| from microbootstrap.instruments.opentelemetry_instrument import ( |
There was a problem hiding this comment.
Давай тут импортнем сразу instrument, чтобы импорт не разрастался
| def __init__(self, **kwargs: typing.Any) -> None: # noqa: ANN401 | ||
| # `broker` argument is positional-only | ||
| super().__init__(kwargs.pop("broker", None), **kwargs) | ||
| self.http_app: ASGIApp = super().__call__ |
There was a problem hiding this comment.
Выглядит как-то оч странно, почему метод - это объект asgiapp?
| super().__init__(kwargs.pop("broker", None), **kwargs) | ||
| self.http_app: ASGIApp = super().__call__ | ||
|
|
||
| def add_http_middleware(self, build_middleware: typing.Callable[[ASGIApp], ASGIApp]) -> None: |
There was a problem hiding this comment.
Поч функцию извне прокидываем? Разве нет какой-то функции, добаляющей миддлварь в фастстриме для веб приложения?
| def add_http_middleware(self, build_middleware: typing.Callable[[ASGIApp], ASGIApp]) -> None: | ||
| self.http_app = build_middleware(self.http_app) | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
There was a problem hiding this comment.
Не оч нравится, что мы так переопределяем поведение объекта приложения, без этого никак не обойтись?
| def build_faststream_route_details_from_scope( | ||
| scope: Scope, | ||
| routes: typing.Iterable[tuple[str, ASGIApp]], | ||
| ) -> tuple[str, dict[str, str]]: | ||
| method: typing.Final = str(scope.get("method", "HTTP")).strip() | ||
| path: typing.Final = scope.get("path") | ||
| # FastStream matches ASGI routes by exact path, unmatched paths get no `http.route` to keep its cardinality low | ||
| if path is None or all(path != route_path for route_path, _ in routes): | ||
| return method, {} | ||
| return build_span_name(method, path), {"http.route": path} |
There was a problem hiding this comment.
Короче, мы тут как будто начинаем делать работу за фастстрим. Это не целевое решение. Давай закинем им в чат, что очень надо это поддержать. Пока предлагаю это не вливать и если очень надо сделать именно так, то это можно переопределить в конкретной репе (или сделать как у нас в репах)
There was a problem hiding this comment.
Можешь даже сам пойти в фастстрим и запилить там ПР. Или зайти к Роме, есть там такой чувак, который за телеметрию отвечает
8493dc5 to
b0eb8b7
Compare
b0eb8b7 to
5f8e27e
Compare
LitestarOpenTelemetryInstrumentationMiddleware read exclusions only from OTEL_PYTHON_LITESTAR_EXCLUDED_URLS, so the opentelemetry_exclude_urls setting was ignored for Litestar. Combine define_exclude_urls() with the env-based list (CombinedExcludeList) and build it once instead of per request. define_exclude_urls moves to BaseOpentelemetryInstrument and build_span_name to instruments/opentelemetry_instrument.py so other bootstrappers can reuse them without importing the Litestar module. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
5f8e27e to
7564f48
Compare
Motivation
LitestarOpenTelemetryInstrumentationMiddlewareread excluded urls only fromOTEL_PYTHON_LITESTAR_EXCLUDED_URLS(orOTEL_PYTHON_EXCLUDED_URLS), so theopentelemetry_exclude_urlssetting documented in the README had no effect for Litestar, andopentelemetry_generate_health_check_spans=Falsedid not suppress health-check spans either.Changes
LitestarOpenTelemetryInstrumentationMiddlewarecombinesdefine_exclude_urls()with the env-based list viaCombinedExcludeList, built once at middleware creation instead of per request.define_exclude_urlsmoves toBaseOpentelemetryInstrumentandbuild_span_nametoinstruments/opentelemetry_instrument.py, so other bootstrappers can reuse them without importing the Litestar module (thelitestarextra may be missing). Add OpenTelemetry instrument for FastMCP #152 relies on this.opentelemetry_exclude_urlsis["/metrics"], and both settings are described precisely.Scope note: an earlier revision of this PR also added
SERVERspans for FastStream ASGI routes. That part was dropped after review; the FastStream bootstrapper is untouched now.Breaking
opentelemetry_exclude_urlsused to be ignored for Litestar. Now the default/metricsexclusion applies, so/metricsstops producing spans, andopentelemetry_generate_health_check_spans=Falsesuppresses health-check spans (the default isTrue). This affects every Litestar user and should go into the release notes.Tests
opentelemetry_exclude_urls=["/internal"]suppresses spans without env vars; other routes still produceSERVERspans.just lint-ciandjust testpass (222 tests).🤖 Generated with Claude Code