The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
use correct otel logger, and normalise otel paths (#15645)
Tom Haynes98f1d6350811
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.pyindex a8cf106b61c..32fde2d0987 100644--- a/litellm/integrations/opentelemetry.py+++ b/litellm/integrations/opentelemetry.py@@ -227,8 +227,9 @@ class OpenTelemetry(CustomLogger):PeriodicExportingMetricReader,)+ normalized_endpoint = self._normalize_otel_endpoint(self.config.endpoint, 'metrics')_metric_exporter = OTLPMetricExporter(- endpoint=self.config.endpoint,+ endpoint=normalized_endpoint,headers=OpenTelemetry._get_headers_dictionary(self.config.headers),preferred_temporality={Histogram: AggregationTemporality.DELTA},)@@ -268,22 +269,20 @@ class OpenTelemetry(CustomLogger):returnfrom opentelemetry._logs import set_logger_provider- from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporterfrom opentelemetry.sdk._logs import LoggerProvider as OTLoggerProviderfrom opentelemetry.sdk._logs.export import BatchLogRecordProcessor# set up log pipelineif logger_provider is None:- logger_provider = OTLoggerProvider()+ litellm_resource = _get_litellm_resource()+ logger_provider = OTLoggerProvider(resource=litellm_resource)# Only add OTLP exporter if we created the logger provider ourselves- logger_provider.add_log_record_processor(- BatchLogRecordProcessor(- OTLPLogExporter(- endpoint=self.config.endpoint,- headers=self._get_headers_dictionary(self.config.headers),- )+ log_exporter = self._get_log_exporter()+ if log_exporter:+ logger_provider.add_log_record_processor(+ BatchLogRecordProcessor(log_exporter) # type: ignore[arg-type])- )+set_logger_provider(logger_provider)def log_success_event(self, kwargs, response_obj, start_time, end_time):@@ -658,10 +657,15 @@ class OpenTelemetry(CustomLogger):if not self.config.enable_events:return- from opentelemetry._logs import LogRecord, get_logger+ from opentelemetry._logs import SeverityNumber, get_logger, get_logger_provider+ from opentelemetry.sdk._logs import LogRecord as SdkLogRecordotel_logger = get_logger(LITELLM_LOGGER_NAME)+ # Get the resource from the logger provider+ logger_provider = get_logger_provider()+ resource = getattr(logger_provider, '_resource', None) or _get_litellm_resource()+parent_ctx = span.get_span_context()provider = (kwargs.get("litellm_params") or {}).get("custom_llm_provider", "Unknown"@@ -676,15 +680,18 @@ class OpenTelemetry(CustomLogger):if self.message_logging and msg.get("content"):attrs["gen_ai.prompt"] = msg["content"]- otel_logger.emit(- LogRecord(- attributes=attrs,- body=msg.copy(),- trace_id=parent_ctx.trace_id,- span_id=parent_ctx.span_id,- trace_flags=parent_ctx.trace_flags,- )+ log_record = SdkLogRecord(+ timestamp=self._to_ns(datetime.now()),+ trace_id=parent_ctx.trace_id,+ span_id=parent_ctx.span_id,+ trace_flags=parent_ctx.trace_flags,+ severity_number=SeverityNumber.INFO,+ severity_text="INFO",+ body=msg.copy(),+ resource=resource,+ attributes=attrs,)+ otel_logger.emit(log_record)# per-choice eventsfor idx, choice in enumerate(response_obj.get("choices", [])):@@ -705,15 +712,18 @@ class OpenTelemetry(CustomLogger):if self.message_logging and body_msg.get("content"):body["message"]["content"] = body_msg["content"]- otel_logger.emit(- LogRecord(- attributes=attrs,- body=body,- trace_id=parent_ctx.trace_id,- span_id=parent_ctx.span_id,- trace_flags=parent_ctx.trace_flags,- )+ log_record = SdkLogRecord(+ timestamp=self._to_ns(datetime.now()),+ trace_id=parent_ctx.trace_id,+ span_id=parent_ctx.span_id,+ trace_flags=parent_ctx.trace_flags,+ severity_number=SeverityNumber.INFO,+ severity_text="INFO",+ body=body,+ resource=resource,+ attributes=attrs,)+ otel_logger.emit(log_record)def _create_guardrail_span(self, kwargs: Optional[dict], context: Optional[Context]@@ -1292,9 +1302,10 @@ class OpenTelemetry(CustomLogger):"OpenTelemetry: intiializing http exporter. Value of OTEL_EXPORTER: %s",self.OTEL_EXPORTER,)+ normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, 'traces')return BatchSpanProcessor(OTLPSpanExporterHTTP(- endpoint=self.OTEL_ENDPOINT, headers=_split_otel_headers+ endpoint=normalized_endpoint, headers=_split_otel_headers),)elif self.OTEL_EXPORTER == "otlp_grpc" or self.OTEL_EXPORTER == "grpc":@@ -1302,9 +1313,10 @@ class OpenTelemetry(CustomLogger):"OpenTelemetry: intiializing grpc exporter. Value of OTEL_EXPORTER: %s",self.OTEL_EXPORTER,)+ normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, 'traces')return BatchSpanProcessor(OTLPSpanExporterGRPC(- endpoint=self.OTEL_ENDPOINT, headers=_split_otel_headers+ endpoint=normalized_endpoint, headers=_split_otel_headers),)else:@@ -1314,6 +1326,145 @@ class OpenTelemetry(CustomLogger):)return BatchSpanProcessor(ConsoleSpanExporter())+ def _get_log_exporter(self):+ """+ Get the appropriate log exporter based on the configuration.+ """+ verbose_logger.debug(+ "OpenTelemetry Logger, initializing log exporter \nself.OTEL_EXPORTER: %s\nself.OTEL_ENDPOINT: %s\nself.OTEL_HEADERS: %s",+ self.OTEL_EXPORTER,+ self.OTEL_ENDPOINT,+ self.OTEL_HEADERS,+ )++ _split_otel_headers = OpenTelemetry._get_headers_dictionary(self.OTEL_HEADERS)++ # Normalize endpoint for logs - ensure it points to /v1/logs instead of /v1/traces+ normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, 'logs')++ verbose_logger.debug(+ "OpenTelemetry: Log endpoint normalized from %s to %s",+ self.OTEL_ENDPOINT,+ normalized_endpoint,+ )++ if hasattr(self.OTEL_EXPORTER, "export"):+ # Custom exporter provided+ verbose_logger.debug(+ "OpenTelemetry: Using custom log exporter. Value of OTEL_EXPORTER: %s",+ self.OTEL_EXPORTER,+ )+ return self.OTEL_EXPORTER++ if self.OTEL_EXPORTER == "console":+ from opentelemetry.sdk._logs.export import ConsoleLogExporter+ verbose_logger.debug(+ "OpenTelemetry: Using console log exporter. Value of OTEL_EXPORTER: %s",+ self.OTEL_EXPORTER,+ )+ return ConsoleLogExporter()+ elif (+ self.OTEL_EXPORTER == "otlp_http"+ or self.OTEL_EXPORTER == "http/protobuf"+ or self.OTEL_EXPORTER == "http/json"+ ):+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter+ verbose_logger.debug(+ "OpenTelemetry: Using HTTP log exporter. Value of OTEL_EXPORTER: %s, endpoint: %s",+ self.OTEL_EXPORTER,+ normalized_endpoint,+ )+ return OTLPLogExporter(+ endpoint=normalized_endpoint, headers=_split_otel_headers+ )+ elif self.OTEL_EXPORTER == "otlp_grpc" or self.OTEL_EXPORTER == "grpc":+ from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter+ verbose_logger.debug(+ "OpenTelemetry: Using gRPC log exporter. Value of OTEL_EXPORTER: %s, endpoint: %s",+ self.OTEL_EXPORTER,+ normalized_endpoint,+ )+ return OTLPLogExporter(+ endpoint=normalized_endpoint, headers=_split_otel_headers+ )+ else:+ verbose_logger.warning(+ "OpenTelemetry: Unknown log exporter '%s', defaulting to console. Supported: console, otlp_http, otlp_grpc",+ self.OTEL_EXPORTER,+ )+ from opentelemetry.sdk._logs.export import ConsoleLogExporter+ return ConsoleLogExporter()++ def _normalize_otel_endpoint(+ self,+ endpoint: Optional[str],+ signal_type: str+ ) -> Optional[str]:+ """+ Normalize the endpoint URL for a specific OpenTelemetry signal type.++ The OTLP exporters expect endpoints to use signal-specific paths:+ - traces: /v1/traces+ - metrics: /v1/metrics+ - logs: /v1/logs++ This method ensures the endpoint has the correct path for the given signal type.++ Args:+ endpoint: The endpoint URL to normalize+ signal_type: The telemetry signal type ('traces', 'metrics', or 'logs')++ Returns:+ Normalized endpoint URL with the correct signal path++ Examples:+ _normalize_otel_endpoint("http://collector:4318/v1/traces", "logs")+ -> "http://collector:4318/v1/logs"++ _normalize_otel_endpoint("http://collector:4318", "traces")+ -> "http://collector:4318/v1/traces"++ _normalize_otel_endpoint("http://collector:4318/v1/logs", "metrics")+ -> "http://collector:4318/v1/metrics"+ """+ if not endpoint:+ return endpoint++ # Validate signal_type+ valid_signals = {'traces', 'metrics', 'logs'}+ if signal_type not in valid_signals:+ verbose_logger.warning(+ "Invalid signal_type '%s' provided to _normalize_otel_endpoint. "+ "Valid values: %s. Returning endpoint unchanged.",+ signal_type,+ valid_signals+ )+ return endpoint++ # Remove trailing slash+ endpoint = endpoint.rstrip('/')++ # Check if endpoint already ends with the correct signal path+ target_path = f'/v1/{signal_type}'+ if endpoint.endswith(target_path):+ return endpoint++ # Replace existing signal path with the target signal path+ other_signals = valid_signals - {signal_type}+ for other_signal in other_signals:+ other_path = f'/v1/{other_signal}'+ if endpoint.endswith(other_path):+ endpoint = endpoint.rsplit('/', 1)[0] + f'/{signal_type}'+ return endpoint++ # No existing signal path found, append the target path+ if not endpoint.endswith('/v1'):+ endpoint = endpoint + target_path+ else:+ endpoint = endpoint + f'/{signal_type}'++ return endpoint+@staticmethoddef _get_headers_dictionary(headers: Optional[Union[str, dict]]) -> Dict[str, str]:"""diff --git a/tests/test_litellm/integrations/test_opentelemetry.py b/tests/test_litellm/integrations/test_opentelemetry.pyindex e605718d29f..fc33b736872 100644--- a/tests/test_litellm/integrations/test_opentelemetry.py+++ b/tests/test_litellm/integrations/test_opentelemetry.py@@ -8,7 +8,7 @@ import time# Adds the grandparent directory to sys.path to allow importing project modulessys.path.insert(0, os.path.abspath("../.."))-from litellm.integrations.opentelemetry import OpenTelemetry+from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfigfrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom opentelemetry.sdk.trace import TracerProvider@@ -806,3 +806,474 @@ class TestOpenTelemetry(unittest.TestCase):otel._maybe_log_raw_request(kwargs, {}, datetime.now(), datetime.now(), MagicMock())mock_tracer.start_span.assert_not_called()+++class TestOpenTelemetryEndpointNormalization(unittest.TestCase):+ """Test suite for the unified _normalize_otel_endpoint method"""++ def test_normalize_traces_endpoint_from_logs_path(self):+ """Test normalizing endpoint with /v1/logs to /v1/traces"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/logs", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_traces_endpoint_from_metrics_path(self):+ """Test normalizing endpoint with /v1/metrics to /v1/traces"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/metrics", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_traces_endpoint_from_base_url(self):+ """Test adding /v1/traces to base URL"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_traces_endpoint_from_v1_path(self):+ """Test adding traces to /v1 path"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_traces_endpoint_already_correct(self):+ """Test endpoint already ending with /v1/traces remains unchanged"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/traces", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_metrics_endpoint_from_traces_path(self):+ """Test normalizing endpoint with /v1/traces to /v1/metrics"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/traces", "metrics")+ self.assertEqual(result, "http://collector:4318/v1/metrics")++ def test_normalize_metrics_endpoint_from_logs_path(self):+ """Test normalizing endpoint with /v1/logs to /v1/metrics"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/logs", "metrics")+ self.assertEqual(result, "http://collector:4318/v1/metrics")++ def test_normalize_metrics_endpoint_from_base_url(self):+ """Test adding /v1/metrics to base URL"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318", "metrics")+ self.assertEqual(result, "http://collector:4318/v1/metrics")++ def test_normalize_metrics_endpoint_already_correct(self):+ """Test endpoint already ending with /v1/metrics remains unchanged"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/metrics", "metrics")+ self.assertEqual(result, "http://collector:4318/v1/metrics")++ def test_normalize_logs_endpoint_from_traces_path(self):+ """Test normalizing endpoint with /v1/traces to /v1/logs"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/traces", "logs")+ self.assertEqual(result, "http://collector:4318/v1/logs")++ def test_normalize_logs_endpoint_from_metrics_path(self):+ """Test normalizing endpoint with /v1/metrics to /v1/logs"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/metrics", "logs")+ self.assertEqual(result, "http://collector:4318/v1/logs")++ def test_normalize_logs_endpoint_from_base_url(self):+ """Test adding /v1/logs to base URL"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318", "logs")+ self.assertEqual(result, "http://collector:4318/v1/logs")++ def test_normalize_logs_endpoint_already_correct(self):+ """Test endpoint already ending with /v1/logs remains unchanged"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/v1/logs", "logs")+ self.assertEqual(result, "http://collector:4318/v1/logs")++ def test_normalize_endpoint_with_trailing_slash(self):+ """Test that trailing slashes are properly handled"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/", "traces")+ self.assertEqual(result, "http://collector:4318/v1/traces")++ def test_normalize_endpoint_none(self):+ """Test that None endpoint returns None"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint(None, "traces")+ self.assertIsNone(result)++ def test_normalize_endpoint_empty_string(self):+ """Test that empty string returns empty string"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("", "traces")+ self.assertEqual(result, "")++ def test_normalize_endpoint_invalid_signal_type(self):+ """Test that invalid signal type returns endpoint unchanged with warning"""+ otel = OpenTelemetry()+ endpoint = "http://collector:4318/v1/traces"++ with patch('litellm._logging.verbose_logger.warning') as mock_warning:+ result = otel._normalize_otel_endpoint(endpoint, "invalid")++ # Should return endpoint unchanged+ self.assertEqual(result, endpoint)++ # Should log a warning+ mock_warning.assert_called_once()+ # Check the warning was called with the expected format string and parameters+ call_args = mock_warning.call_args[0]+ self.assertIn("Invalid signal_type", call_args[0])+ self.assertEqual(call_args[1], "invalid") # signal_type parameter+ self.assertEqual(call_args[2], {'traces', 'metrics', 'logs'}) # valid_signals parameter++ def test_normalize_endpoint_https(self):+ """Test normalization works with https URLs"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("https://collector.example.com:4318", "logs")+ self.assertEqual(result, "https://collector.example.com:4318/v1/logs")++ def test_normalize_endpoint_with_path_prefix(self):+ """Test normalization works with URLs that have path prefixes"""+ otel = OpenTelemetry()+ result = otel._normalize_otel_endpoint("http://collector:4318/otel/v1/traces", "logs")+ # Should replace the final /traces with /logs+ self.assertEqual(result, "http://collector:4318/otel/v1/logs")++ def test_normalize_endpoint_consistency_across_signals(self):+ """Test that normalization is consistent for all signal types from the same base"""+ otel = OpenTelemetry()+ base = "http://collector:4318"++ traces_result = otel._normalize_otel_endpoint(base, "traces")+ metrics_result = otel._normalize_otel_endpoint(base, "metrics")+ logs_result = otel._normalize_otel_endpoint(base, "logs")++ # All should have the same base with different signal paths+ self.assertEqual(traces_result, "http://collector:4318/v1/traces")+ self.assertEqual(metrics_result, "http://collector:4318/v1/metrics")+ self.assertEqual(logs_result, "http://collector:4318/v1/logs")++ def test_normalize_endpoint_signal_switching(self):+ """Test switching between different signal types on the same endpoint"""+ otel = OpenTelemetry()++ # Start with traces+ endpoint = "http://collector:4318/v1/traces"++ # Switch to metrics+ metrics = otel._normalize_otel_endpoint(endpoint, "metrics")+ self.assertEqual(metrics, "http://collector:4318/v1/metrics")++ # Switch to logs+ logs = otel._normalize_otel_endpoint(metrics, "logs")+ self.assertEqual(logs, "http://collector:4318/v1/logs")++ # Switch back to traces+ traces = otel._normalize_otel_endpoint(logs, "traces")+ self.assertEqual(traces, "http://collector:4318/v1/traces")+++class TestOpenTelemetryProtocolSelection(unittest.TestCase):+ """Test suite for verifying correct exporter selection based on protocol"""++ def test_get_span_processor_uses_http_exporter_for_otlp_http(self):+ """Test that otlp_http protocol uses OTLPSpanExporterHTTP"""+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterHTTP,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint="http://collector:4318"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify it's a BatchSpanProcessor+ self.assertIsInstance(processor, BatchSpanProcessor)++ # Verify the exporter is the HTTP variant+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterHTTP)++ def test_get_span_processor_uses_grpc_exporter_for_otlp_grpc(self):+ """Test that otlp_grpc protocol uses OTLPSpanExporterGRPC"""+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterGRPC,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig(+ exporter="otlp_grpc",+ endpoint="http://collector:4317"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify it's a BatchSpanProcessor+ self.assertIsInstance(processor, BatchSpanProcessor)++ # Verify the exporter is the gRPC variant+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterGRPC)++ def test_get_span_processor_uses_grpc_exporter_for_grpc_alias(self):+ """Test that 'grpc' protocol alias uses OTLPSpanExporterGRPC"""+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterGRPC,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig(+ exporter="grpc",+ endpoint="http://collector:4317"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify it's a BatchSpanProcessor+ self.assertIsInstance(processor, BatchSpanProcessor)++ # Verify the exporter is the gRPC variant+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterGRPC)++ def test_get_span_processor_uses_http_exporter_for_http_protobuf(self):+ """Test that http/protobuf protocol uses OTLPSpanExporterHTTP"""+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterHTTP,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig(+ exporter="http/protobuf",+ endpoint="http://collector:4318"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify it's a BatchSpanProcessor+ self.assertIsInstance(processor, BatchSpanProcessor)++ # Verify the exporter is the HTTP variant+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterHTTP)++ def test_get_span_processor_uses_console_exporter_for_console(self):+ """Test that console protocol uses ConsoleSpanExporter"""+ from opentelemetry.sdk.trace.export import (+ BatchSpanProcessor,+ ConsoleSpanExporter,+ )++ config = OpenTelemetryConfig(exporter="console")+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify it's a BatchSpanProcessor+ self.assertIsInstance(processor, BatchSpanProcessor)++ # Verify the exporter is the console variant+ self.assertIsInstance(processor.span_exporter, ConsoleSpanExporter)++ def test_get_log_exporter_uses_http_exporter_for_otlp_http(self):+ """Test that otlp_http protocol uses HTTP OTLPLogExporter"""+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter++ config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint="http://collector:4318",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the exporter is the HTTP variant+ self.assertIsInstance(exporter, OTLPLogExporter)++ # Check that it's from the http module by checking the module name+ self.assertIn('http', exporter.__class__.__module__)++ def test_get_log_exporter_uses_grpc_exporter_for_otlp_grpc(self):+ """Test that otlp_grpc protocol uses gRPC OTLPLogExporter"""+ from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter++ config = OpenTelemetryConfig(+ exporter="otlp_grpc",+ endpoint="http://collector:4317",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the exporter is the gRPC variant+ self.assertIsInstance(exporter, OTLPLogExporter)++ # Check that it's from the grpc module by checking the module name+ self.assertIn('grpc', exporter.__class__.__module__)++ def test_get_log_exporter_uses_grpc_exporter_for_grpc_alias(self):+ """Test that 'grpc' protocol alias uses gRPC OTLPLogExporter"""+ from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter++ config = OpenTelemetryConfig(+ exporter="grpc",+ endpoint="http://collector:4317",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the exporter is the gRPC variant+ self.assertIsInstance(exporter, OTLPLogExporter)++ # Check that it's from the grpc module by checking the module name+ self.assertIn('grpc', exporter.__class__.__module__)++ def test_get_log_exporter_uses_console_exporter_for_console(self):+ """Test that console protocol uses ConsoleLogExporter"""+ from opentelemetry.sdk._logs.export import ConsoleLogExporter++ config = OpenTelemetryConfig(+ exporter="console",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the exporter is the console variant+ self.assertIsInstance(exporter, ConsoleLogExporter)++ def test_get_log_exporter_defaults_to_console_for_unknown_protocol(self):+ """Test that unknown protocol defaults to ConsoleLogExporter with warning"""+ from opentelemetry.sdk._logs.export import ConsoleLogExporter++ config = OpenTelemetryConfig(+ exporter="unknown_protocol",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ with patch('litellm._logging.verbose_logger.warning') as mock_warning:+ exporter = otel._get_log_exporter()++ # Verify the exporter defaults to console+ self.assertIsInstance(exporter, ConsoleLogExporter)++ # Verify a warning was logged+ mock_warning.assert_called_once()+ args = mock_warning.call_args[0]+ self.assertIn("Unknown log exporter", args[0])+ self.assertIn("unknown_protocol", args[1])++ @patch.dict(os.environ, {"OTEL_EXPORTER": "otlp_http", "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector:4318"}, clear=False)+ def test_protocol_selection_from_environment_http(self):+ """Test that protocol selection works correctly from environment variables for HTTP"""+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterHTTP,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig.from_env()+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify the HTTP exporter is used+ self.assertIsInstance(processor, BatchSpanProcessor)+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterHTTP)++ @patch.dict(os.environ, {"OTEL_EXPORTER": "otlp_grpc", "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector:4317"}, clear=False)+ def test_protocol_selection_from_environment_grpc(self):+ """Test that protocol selection works correctly from environment variables for gRPC"""+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (+ OTLPSpanExporter as OTLPSpanExporterGRPC,+ )+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ config = OpenTelemetryConfig.from_env()+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify the gRPC exporter is used+ self.assertIsInstance(processor, BatchSpanProcessor)+ self.assertIsInstance(processor.span_exporter, OTLPSpanExporterGRPC)++ def test_http_exporter_endpoint_normalization_for_traces(self):+ """Test that HTTP trace exporter gets properly normalized endpoint"""+ config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint="http://collector:4318"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify the endpoint was normalized to include /v1/traces+ # Access the private _endpoint attribute if available+ if hasattr(processor.span_exporter, '_endpoint'):+ self.assertEqual(processor.span_exporter._endpoint, "http://collector:4318/v1/traces") # type: ignore[attr-defined]++ def test_grpc_exporter_endpoint_normalization_for_traces(self):+ """Test that gRPC trace exporter gets properly normalized endpoint"""+ config = OpenTelemetryConfig(+ exporter="otlp_grpc",+ endpoint="http://collector:4317"+ )+ otel = OpenTelemetry(config=config)++ processor = otel._get_span_processor()++ # Verify the endpoint was normalized to include /v1/traces+ # Note: gRPC exporters strip the http:// prefix, so we check for the normalized path+ if hasattr(processor.span_exporter, '_endpoint'):+ # gRPC exporter strips http:// prefix+ self.assertIn('collector:4317', processor.span_exporter._endpoint) # type: ignore[attr-defined]+ # The endpoint should have been normalized with /v1/traces before being passed to gRPC exporter+ # We verify this by checking the normalization function was called correctly+ normalized = otel._normalize_otel_endpoint("http://collector:4317", "traces")+ self.assertEqual(normalized, "http://collector:4317/v1/traces")++ def test_http_log_exporter_endpoint_normalization_for_logs(self):+ """Test that HTTP log exporter gets properly normalized endpoint"""+ config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint="http://collector:4318/v1/traces",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the endpoint was normalized to /v1/logs (not /v1/traces)+ # Access the private _endpoint attribute if available+ if hasattr(exporter, '_endpoint'):+ self.assertEqual(exporter._endpoint, "http://collector:4318/v1/logs") # type: ignore[attr-defined]++ def test_grpc_log_exporter_endpoint_normalization_for_logs(self):+ """Test that gRPC log exporter gets properly normalized endpoint"""+ config = OpenTelemetryConfig(+ exporter="otlp_grpc",+ endpoint="http://collector:4317/v1/traces",+ enable_events=True+ )+ otel = OpenTelemetry(config=config)++ exporter = otel._get_log_exporter()++ # Verify the endpoint was normalized to /v1/logs (not /v1/traces)+ # Note: gRPC exporters strip the http:// prefix, so we check for the normalized path+ if hasattr(exporter, '_endpoint'):+ # gRPC exporter strips http:// prefix+ self.assertIn('collector:4317', exporter._endpoint) # type: ignore[attr-defined]+ # The endpoint should have been normalized with /v1/logs before being passed to gRPC exporter+ # We verify this by checking the normalization function was called correctly+ normalized = otel._normalize_otel_endpoint("http://collector:4317/v1/traces", "logs")+ self.assertEqual(normalized, "http://collector:4317/v1/logs")