Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,9 @@ Parameters description:
- `opentelemetry_insecure` - is opentelemetry connection secure.
- `opentelemetry_container_name` - will be passed to the `Resource`.
- `opentelemetry_instrumentors` - a list of extra instrumentors.
- `opentelemetry_exclude_urls` - extra url regexes that produce no server spans (empty by default). `prometheus_metrics_path` is always excluded; for FastAPI and FastMCP it is matched as a whole path, so `/metrics` excludes neither `/api/metrics` nor `/metrics-report`. For Litestar they are combined with `OTEL_PYTHON_LITESTAR_EXCLUDED_URLS` (or `OTEL_PYTHON_EXCLUDED_URLS`), for FastMCP with `OTEL_PYTHON_STARLETTE_EXCLUDED_URLS` (or `OTEL_PYTHON_EXCLUDED_URLS`).
- `opentelemetry_exclude_urls` - extra url regexes that produce no server spans (empty by default). `prometheus_metrics_path` is always excluded and matched as a whole path on every framework, so `/metrics` excludes neither `/api/metrics` nor `/metrics-report`. For Litestar they are combined with `OTEL_PYTHON_LITESTAR_EXCLUDED_URLS` (or `OTEL_PYTHON_EXCLUDED_URLS`), for FastMCP with `OTEL_PYTHON_STARLETTE_EXCLUDED_URLS` (or `OTEL_PYTHON_EXCLUDED_URLS`).

For Litestar the tracing is wired through Litestar's own [`OpenTelemetryPlugin`](https://docs.litestar.dev/2/reference/plugins/opentelemetry.html). Server spans are named by the route template, e.g. `GET /users/{user_id}`, and carry it in `http.route`; requests that match no route produce a span named after the HTTP method only, without `http.route`.
- `opentelemetry_log_traces` - traces will be logged to stdout.
- `opentelemetry_generate_health_check_spans` - generate spans for health check handlers if `True`; if `False`, `health_checks_path` is added to the excluded urls.
- `opentelemetry_baggage_span_attributes` - maps allowed baggage keys to attributes added to local server and consumer spans.
Expand Down
85 changes: 33 additions & 52 deletions microbootstrap/bootstrappers/litestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@
import typing_extensions
from litestar import openapi
from litestar.config.cors import CORSConfig as LitestarCorsConfig
from litestar.contrib.opentelemetry.config import (
OpenTelemetryConfig as LitestarOpentelemetryConfig,
)
from litestar.contrib.prometheus import PrometheusConfig, PrometheusController
from litestar.middleware import ASGIMiddleware
from litestar.openapi.plugins import SwaggerRenderPlugin
from litestar.types.asgi_types import ASGIApp, Scope
from litestar.plugins.opentelemetry import OpenTelemetryConfig as LitestarOpentelemetryConfig
from litestar.plugins.opentelemetry import OpenTelemetryPlugin
from litestar_offline_docs import generate_static_files_config
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
from opentelemetry.util.http import ExcludeList, get_excluded_urls
from opentelemetry import trace
from sentry_sdk.integrations.litestar import LitestarIntegration

from microbootstrap.bootstrappers.base import ApplicationBootstrapper
Expand Down Expand Up @@ -59,9 +56,7 @@ class AcceptVersionedOperation(openapi.spec.Operation):


if typing.TYPE_CHECKING:
from litestar.contrib.opentelemetry import OpenTelemetryConfig
from litestar.types import ASGIApp, Scope
from litestar.types.asgi_types import Receive, Send
from litestar.types import ASGIApp, Receive, Scope, Send


class LitestarBootstrapper(
Expand Down Expand Up @@ -253,58 +248,44 @@ def build_litestar_route_details_from_scope(
"""
path_template: typing.Final = scope.get("path_template")
method: typing.Final = str(scope.get("method", "HTTP")).strip()
if path_template is not None:
path_template_stripped: typing.Final = path_template.strip()
span_name: typing.Final = opentelemetry_instrument.build_span_name(method, path_template_stripped)
return span_name, {"http.route": path_template_stripped}

path: typing.Final = scope.get("path")
if path is not None:
path_stripped: typing.Final = path.strip()
return opentelemetry_instrument.build_span_name(method, path_stripped), {"http.route": path_stripped}
return method, {}


class LitestarOpenTelemetryInstrumentationMiddleware(ASGIMiddleware):
def __init__(self, config: OpenTelemetryConfig, exclude_urls: typing.Sequence[str] = ()) -> None:
self.config = config
self.excluded_urls = opentelemetry_instrument.CombinedExcludeList(
ExcludeList(exclude_urls),
get_excluded_urls(self.config.exclude_urls_env_key),
)

def create_open_telemetry_middleware(self, app: ASGIApp) -> OpenTelemetryMiddleware:
return OpenTelemetryMiddleware(
app=app,
client_request_hook=self.config.client_request_hook_handler,
client_response_hook=self.config.client_response_hook_handler,
default_span_details=build_litestar_route_details_from_scope,
excluded_urls=self.excluded_urls,
meter=self.config.meter,
meter_provider=self.config.meter_provider,
server_request_hook=self.config.server_request_hook_handler,
tracer_provider=self.config.tracer_provider,
)

# Unmatched paths get only the method and no `http.route`: a raw path would let scanners explode span cardinality
if path_template is None:
return method, {}
path_template_stripped: typing.Final = path_template.strip()
return opentelemetry_instrument.build_span_name(method, path_template_stripped), {
"http.route": path_template_stripped
}


class LitestarOpentelemetryRouteMiddleware(ASGIMiddleware):
# `OpenTelemetryPlugin` wraps the whole application, so its span is created before routing with the raw path.
# This middleware runs inside the route handler stack, where `path_template` is known, and renames the span.
async def handle(self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) -> None:
await self.create_open_telemetry_middleware(next_app)(scope, receive, send) # type: ignore[arg-type]
server_span: typing.Final = trace.get_current_span()
if server_span.is_recording():
span_name, attributes = build_litestar_route_details_from_scope(scope)
server_span.update_name(span_name)
server_span.set_attributes(attributes)
await next_app(scope, receive, send)


@LitestarBootstrapper.use_instrument()
class LitestarOpentelemetryInstrument(opentelemetry_instrument.OpentelemetryInstrument):
def bootstrap_before(self) -> dict[str, typing.Any]:
return {
"middleware": [
LitestarOpenTelemetryInstrumentationMiddleware(
LitestarOpentelemetryConfig(
tracer_provider=self.tracer_provider,
middleware_class=LitestarOpenTelemetryInstrumentationMiddleware, # type: ignore[arg-type]
),
exclude_urls=self.define_exclude_urls(),
)
]
"plugins": [OpenTelemetryPlugin(self.build_litestar_opentelemetry_config())],
"middleware": [LitestarOpentelemetryRouteMiddleware()],
}

def build_litestar_opentelemetry_config(self) -> LitestarOpentelemetryConfig:
# `exclude` bypasses the plugin middleware for the configured paths; the plugin itself still honors
# `OTEL_PYTHON_LITESTAR_EXCLUDED_URLS` through `exclude_urls_env_key`.
return LitestarOpentelemetryConfig(
tracer_provider=self.tracer_provider,
scope_span_details_extractor=build_litestar_route_details_from_scope,
exclude=self.define_excluded_path_patterns() or None,
)


@LitestarBootstrapper.use_instrument()
class LitestarLoggingInstrument(LoggingInstrument):
Expand Down
7 changes: 7 additions & 0 deletions microbootstrap/instruments/opentelemetry_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,13 @@ def define_excluded_url_patterns(self) -> list[str]:
]
return [*self.instrument_config.opentelemetry_exclude_urls, *anchored_paths]

def define_excluded_path_patterns(self) -> list[str]:
# The path-based counterpart of define_excluded_url_patterns() for middlewares that search a bare path
anchored_paths: typing.Final = [
rf"^{re.escape(path.rstrip('/'))}(?:/|$)" for path in self.define_excluded_paths() if path.rstrip("/")
]
return [*self.instrument_config.opentelemetry_exclude_urls, *anchored_paths]

def is_ready(self) -> bool:
return (
bool(self.instrument_config.opentelemetry_endpoint)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fastapi = [
"prometheus-fastapi-instrumentator>=7.1",
]
litestar = [
"litestar>=2.21.1",
"litestar>=2.22.0",
"litestar-offline-docs>=1",
"prometheus-client>=0.20",
]
Expand Down
Loading
Loading