From 5abb30d04165b4ea36c0d14e9dfbb4eb27fa932c Mon Sep 17 00:00:00 2001 From: Artur Shiriev Date: Sat, 2 May 2026 18:20:46 +0300 Subject: [PATCH] perf: hoist OTel import in tracer_injection to module level tracer_injection runs once per log line. The previous in-function `try / from opentelemetry import trace / except ImportError` paid the try-machinery and import-lookup cost on every call, even though import_checker.is_opentelemetry_installed already settles the question at startup. Move the import into a module-level guard parallel to the existing is_structlog_installed block, defining a no-op fallback tracer_injection in the else branch for environments without OTel. Co-Authored-By: Claude Opus 4.7 --- .../instruments/logging_instrument.py | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/lite_bootstrap/instruments/logging_instrument.py b/lite_bootstrap/instruments/logging_instrument.py index fe1e9d8..0481756 100644 --- a/lite_bootstrap/instruments/logging_instrument.py +++ b/lite_bootstrap/instruments/logging_instrument.py @@ -18,6 +18,28 @@ import structlog +if import_checker.is_opentelemetry_installed: + from opentelemetry import trace + + def tracer_injection(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": + current_span = trace.get_current_span() + if not current_span.is_recording(): + event_dict["tracing"] = {} + return event_dict + + current_span_context = current_span.get_span_context() + event_dict["tracing"] = { + "span_id": trace.format_span_id(current_span_context.span_id), + "trace_id": trace.format_trace_id(current_span_context.trace_id), + } + return event_dict + +else: # pragma: no cover + + def tracer_injection(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": + return event_dict + + ScopeType = typing.MutableMapping[str, typing.Any] @@ -32,25 +54,6 @@ class RequestProtocol(typing.Protocol): method: str -def tracer_injection(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": - try: - from opentelemetry import trace # noqa: PLC0415 - except ImportError: # pragma: no cover - return event_dict - - current_span = trace.get_current_span() - if not current_span.is_recording(): - event_dict["tracing"] = {} - return event_dict - - current_span_context = current_span.get_span_context() - event_dict["tracing"] = { - "span_id": trace.format_span_id(current_span_context.span_id), - "trace_id": trace.format_trace_id(current_span_context.trace_id), - } - return event_dict - - if import_checker.is_structlog_installed: class MemoryLoggerFactory(structlog.stdlib.LoggerFactory):