Initialize the global OTEL tracer provider. Idempotent. No-op when tracing isn't configured, so callers can invoke unconditionally from CLI entry points.
(service_name: str)
| 50 | |
| 51 | |
| 52 | def init_tracing(service_name: str) -> None: |
| 53 | """Initialize the global OTEL tracer provider. |
| 54 | |
| 55 | Idempotent. No-op when tracing isn't configured, so callers can invoke |
| 56 | unconditionally from CLI entry points. |
| 57 | """ |
| 58 | global _initialized |
| 59 | if _initialized: |
| 60 | return |
| 61 | if not _tracing_enabled(): |
| 62 | return |
| 63 | |
| 64 | try: |
| 65 | from opentelemetry.sdk.resources import Resource |
| 66 | from opentelemetry.sdk.trace import TracerProvider |
| 67 | from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 68 | except ImportError as exc: |
| 69 | _log.warning("OTEL SDK not installed; tracing disabled: %s", exc) |
| 70 | return |
| 71 | |
| 72 | with _init_lock: |
| 73 | if _initialized: |
| 74 | return |
| 75 | |
| 76 | provider = TracerProvider( |
| 77 | resource=Resource.create({"service.name": service_name}) |
| 78 | ) |
| 79 | |
| 80 | if (path := _traces_file_path()) is not None: |
| 81 | from .file_exporter import OTLPJsonFileExporter |
| 82 | |
| 83 | provider.add_span_processor(BatchSpanProcessor(OTLPJsonFileExporter(path))) |
| 84 | _log.info("OTEL file exporter enabled (path=%s).", path) |
| 85 | |
| 86 | if _http_endpoint_set(): |
| 87 | try: |
| 88 | from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( |
| 89 | OTLPSpanExporter, |
| 90 | ) |
| 91 | except ImportError: |
| 92 | _log.warning( |
| 93 | "opentelemetry-exporter-otlp-proto-http not installed; " |
| 94 | "HTTP export disabled." |
| 95 | ) |
| 96 | else: |
| 97 | provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) |
| 98 | _log.info("OTEL HTTP exporter enabled.") |
| 99 | |
| 100 | trace.set_tracer_provider(provider) |
| 101 | atexit.register(provider.shutdown) |
| 102 | |
| 103 | try: |
| 104 | from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor |
| 105 | |
| 106 | HTTPXClientInstrumentor().instrument() |
| 107 | except ImportError: |
| 108 | _log.warning( |
| 109 | "opentelemetry-instrumentation-httpx not installed — LiteLLM " |