|
35 | 35 | from opentelemetry.trace import SpanKind, Status, StatusCode |
36 | 36 |
|
37 | 37 | _HAS_OPENTELEMETRY = True |
| 38 | + # Safe to cache at import time: opentelemetry.trace.get_tracer() returns a |
| 39 | + # ProxyTracer when no real TracerProvider is registered yet, and that proxy |
| 40 | + # transparently starts delegating to the real tracer once the application |
| 41 | + # calls trace.set_tracer_provider() later, so this doesn't bind us to a |
| 42 | + # permanently-inert no-op tracer. |
| 43 | + _TRACER: Optional[Tracer] = trace.get_tracer("PyMongo", __version__) |
38 | 44 | except ImportError: |
39 | 45 | _HAS_OPENTELEMETRY = False |
| 46 | + _TRACER = None |
40 | 47 |
|
41 | 48 | if TYPE_CHECKING: |
42 | 49 | from opentelemetry.trace import Span, Tracer |
@@ -99,11 +106,6 @@ def _is_tracing_enabled(tracing_options: Optional[TracingOptions]) -> bool: |
99 | 106 | return _env_truthy(_OTEL_ENABLED_ENV) |
100 | 107 |
|
101 | 108 |
|
102 | | -def _get_tracer() -> Tracer: |
103 | | - """Return a Tracer scoped to this driver's name and version.""" |
104 | | - return trace.get_tracer("PyMongo", __version__) |
105 | | - |
106 | | - |
107 | 109 | def _get_query_text_max_length(tracing_options: Optional[TracingOptions]) -> int: |
108 | 110 | """Return the configured db.query.text truncation length, or 0 to omit the attribute. |
109 | 111 |
|
@@ -236,8 +238,8 @@ def start_command_span( |
236 | 238 | if max_query_text_length > 0: |
237 | 239 | attributes["db.query.text"] = _build_query_text(cmd, max_query_text_length) |
238 | 240 |
|
239 | | - tracer = _get_tracer() |
240 | | - return tracer.start_span(command_name, kind=SpanKind.CLIENT, attributes=attributes) |
| 241 | + assert _TRACER is not None # _is_tracing_enabled already checked _HAS_OPENTELEMETRY |
| 242 | + return _TRACER.start_span(command_name, kind=SpanKind.CLIENT, attributes=attributes) |
241 | 243 |
|
242 | 244 |
|
243 | 245 | def end_command_span_success(span: Optional[Span], reply: _DocumentOut) -> None: |
|
0 commit comments