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
fix(proxy): build configured logging callbacks at boot so a broken callback fails startup instead of the first request (#46378)
ryan-crabbe-berri829d50990dcd
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 7b965dea28a..944d3c57f7d 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -22,7 +22,6 @@ from httpx import Responsefrom pydantic import BaseModel, JsonValueimport litellm-from litellm import _custom_logger_compatible_callbacks_literalfrom litellm._internal_context import post_response_phasefrom litellm._logging import (is_debugging_on,@@ -4575,712 +4574,738 @@ def set_callbacks(raise e-def _init_custom_logger_compatible_class(- logging_integration: _custom_logger_compatible_callbacks_literal,+def build_custom_logger_compatible_class(+ logging_integration: str,internal_usage_cache: DualCache | None,llm_router: object,- custom_logger_init_args: dict[str, object] | None = {},+ custom_logger_init_args: dict[str, object] | None = None,) -> CustomLogger | None:- """- Initialize a custom logger compatible class- """- try:- custom_logger_init_args_value: Final[dict[str, object]] = custom_logger_init_args or {}- if logging_integration == "agentops": # Add AgentOps initialization- _v2 = _maybe_construct_otel_v2("agentops", _in_memory_loggers)- if _v2 is not None:- return _v2- for callback in _in_memory_loggers:- if isinstance(callback, AgentOps):- return callback-- agentops_logger: Final = AgentOps()- _in_memory_loggers.append(agentops_logger)- return agentops_logger- elif logging_integration == "lago":- for callback in _in_memory_loggers:- if isinstance(callback, LagoLogger):- return callback-- lago_logger: Final = LagoLogger()- _in_memory_loggers.append(lago_logger)- return lago_logger- elif logging_integration == "openmeter":- for callback in _in_memory_loggers:- if isinstance(callback, OpenMeterLogger):- return callback-- _openmeter_logger: Final = OpenMeterLogger()- _in_memory_loggers.append(_openmeter_logger)- return _openmeter_logger- elif logging_integration == "posthog":- for callback in _in_memory_loggers:- if isinstance(callback, PostHogLogger):- return callback-- _posthog_logger: Final = PostHogLogger()- _in_memory_loggers.append(_posthog_logger)- return _posthog_logger- elif logging_integration == "braintrust":- from litellm.integrations.braintrust_logging import BraintrustLogger-- for callback in _in_memory_loggers:- if isinstance(callback, BraintrustLogger):- return callback-- braintrust_logger: Final = BraintrustLogger()- _in_memory_loggers.append(braintrust_logger)- return braintrust_logger- elif logging_integration == "langsmith":- for callback in _in_memory_loggers:- if isinstance(callback, LangsmithLogger):- return callback-- _langsmith_logger: Final = LangsmithLogger()- _in_memory_loggers.append(_langsmith_logger)- return _langsmith_logger- elif logging_integration == "argilla":- for callback in _in_memory_loggers:- if isinstance(callback, ArgillaLogger):- return callback-- _argilla_logger: Final = ArgillaLogger()- _in_memory_loggers.append(_argilla_logger)- return _argilla_logger- elif logging_integration == "literalai":- for callback in _in_memory_loggers:- if isinstance(callback, LiteralAILogger):- return callback-- _literalai_logger: Final = LiteralAILogger()- _in_memory_loggers.append(_literalai_logger)- return _literalai_logger- elif logging_integration == "litellm_agent":- for callback in _in_memory_loggers:- if isinstance(callback, LiteLLMAgentModelResolver):- return callback-- _litellm_agent_resolver: Final = LiteLLMAgentModelResolver()- _in_memory_loggers.append(_litellm_agent_resolver)- return _litellm_agent_resolver- elif logging_integration == "prometheus":- PrometheusLogger: Final = _get_cached_prometheus_logger()-- for callback in _in_memory_loggers:- if isinstance(callback, PrometheusLogger):- return callback-- _prometheus_logger: Final = PrometheusLogger()- _in_memory_loggers.append(_prometheus_logger)- return _prometheus_logger- elif logging_integration == "datadog":- # Check if team-scoped credentials are provided- _dd_api_key: Final = custom_logger_init_args_value.get("dd_api_key")- _dd_site: Final = custom_logger_init_args_value.get("dd_site")- _dd_agent_host: Final = custom_logger_init_args_value.get("dd_agent_host")- _dd_agent_port: Final = custom_logger_init_args_value.get("dd_agent_port")-- if _dd_api_key or _dd_site or _dd_agent_host:- # Team-scoped credentials: use DynamicLoggingCache for per-credential isolation- from litellm.integrations.datadog.datadog_team_handler import (- DataDogHandler,- )-- return DataDogHandler.get_datadog_logger_for_request(- standard_callback_dynamic_params=cast( # cast-ok: callback options come from dynamic config- StandardCallbackDynamicParams, custom_logger_init_args_value- ),- in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,- )-- # Global (env-var based): reuse cached instance- for callback in _in_memory_loggers:- if isinstance(callback, DataDogLogger):- return callback-- _datadog_logger: Final = DataDogLogger()- _in_memory_loggers.append(_datadog_logger)- return _datadog_logger- elif logging_integration == "datadog_metrics":- for callback in _in_memory_loggers:- if isinstance(callback, DatadogMetricsLogger):- return callback-- _datadog_metrics_logger: Final = DatadogMetricsLogger()- _in_memory_loggers.append(_datadog_metrics_logger)- return _datadog_metrics_logger- elif logging_integration == "datadog_llm_observability":- _datadog_llm_obs_logger: Final = DataDogLLMObsLogger()- _in_memory_loggers.append(_datadog_llm_obs_logger)- return _datadog_llm_obs_logger- elif logging_integration == "azure_sentinel":- for callback in _in_memory_loggers:- if isinstance(callback, AzureSentinelLogger):- return callback-- _azure_sentinel_logger: Final = AzureSentinelLogger()- _in_memory_loggers.append(_azure_sentinel_logger)- return _azure_sentinel_logger- elif logging_integration == "gcs_bucket":- for callback in _in_memory_loggers:- if isinstance(callback, GCSBucketLogger):- return callback-- _gcs_bucket_logger: Final = GCSBucketLogger()- _in_memory_loggers.append(_gcs_bucket_logger)- return _gcs_bucket_logger- elif logging_integration == "s3_v2":- for callback in _in_memory_loggers:- if isinstance(callback, S3V2Logger):- return callback-- _s3_v2_logger: Final = S3V2Logger()- _in_memory_loggers.append(_s3_v2_logger)- return _s3_v2_logger- elif logging_integration == "clickhouse":- for callback in _in_memory_loggers:- if isinstance(callback, ClickHouseSpendLogger):- return callback-- _clickhouse_spend_logger: Final = ClickHouseSpendLogger()- _in_memory_loggers.append(_clickhouse_spend_logger)- return _clickhouse_spend_logger- elif logging_integration == "pointfive":- for callback in _in_memory_loggers:- if isinstance(callback, PointFiveLogger):- return callback-- _pointfive_logger: Final = PointFiveLogger()- _in_memory_loggers.append(_pointfive_logger)- return _pointfive_logger- elif logging_integration == "zerobus":- for callback in _in_memory_loggers:- if isinstance(callback, ZerobusLogger):- return callback-- _zerobus_logger: Final = ZerobusLogger()- _in_memory_loggers.append(_zerobus_logger)- return _zerobus_logger- elif logging_integration == "aws_sqs":- for callback in _in_memory_loggers:- if isinstance(callback, SQSLogger):- return callback-- _aws_sqs_logger: Final = SQSLogger()- _in_memory_loggers.append(_aws_sqs_logger)- return _aws_sqs_logger- elif logging_integration == "azure_storage":- for callback in _in_memory_loggers:- if isinstance(callback, AzureBlobStorageLogger):- return callback-- _azure_storage_logger: Final = AzureBlobStorageLogger()- _in_memory_loggers.append(_azure_storage_logger)- return _azure_storage_logger- elif logging_integration == "opik":- for callback in _in_memory_loggers:- if isinstance(callback, OpikLogger):- return callback-- _opik_logger: Final = OpikLogger()- _in_memory_loggers.append(_opik_logger)- return _opik_logger- elif logging_integration == "arize":- _v2 = _maybe_construct_otel_v2("arize", _in_memory_loggers)- if _v2 is not None:- return _v2- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,+ custom_logger_init_args_value: Final[dict[str, object]] = custom_logger_init_args or {}+ if logging_integration == "agentops": # Add AgentOps initialization+ _v2 = _maybe_construct_otel_v2("agentops", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ for callback in _in_memory_loggers:+ if isinstance(callback, AgentOps):+ return callback++ agentops_logger: Final = AgentOps()+ _in_memory_loggers.append(agentops_logger)+ return agentops_logger+ elif logging_integration == "lago":+ for callback in _in_memory_loggers:+ if isinstance(callback, LagoLogger):+ return callback++ lago_logger: Final = LagoLogger()+ _in_memory_loggers.append(lago_logger)+ return lago_logger+ elif logging_integration == "openmeter":+ for callback in _in_memory_loggers:+ if isinstance(callback, OpenMeterLogger):+ return callback++ _openmeter_logger: Final = OpenMeterLogger()+ _in_memory_loggers.append(_openmeter_logger)+ return _openmeter_logger+ elif logging_integration == "posthog":+ for callback in _in_memory_loggers:+ if isinstance(callback, PostHogLogger):+ return callback++ _posthog_logger: Final = PostHogLogger()+ _in_memory_loggers.append(_posthog_logger)+ return _posthog_logger+ elif logging_integration == "braintrust":+ from litellm.integrations.braintrust_logging import BraintrustLogger++ for callback in _in_memory_loggers:+ if isinstance(callback, BraintrustLogger):+ return callback++ braintrust_logger: Final = BraintrustLogger()+ _in_memory_loggers.append(braintrust_logger)+ return braintrust_logger+ elif logging_integration == "langsmith":+ for callback in _in_memory_loggers:+ if isinstance(callback, LangsmithLogger):+ return callback++ _langsmith_logger: Final = LangsmithLogger()+ _in_memory_loggers.append(_langsmith_logger)+ return _langsmith_logger+ elif logging_integration == "argilla":+ for callback in _in_memory_loggers:+ if isinstance(callback, ArgillaLogger):+ return callback++ _argilla_logger: Final = ArgillaLogger()+ _in_memory_loggers.append(_argilla_logger)+ return _argilla_logger+ elif logging_integration == "literalai":+ for callback in _in_memory_loggers:+ if isinstance(callback, LiteralAILogger):+ return callback++ _literalai_logger: Final = LiteralAILogger()+ _in_memory_loggers.append(_literalai_logger)+ return _literalai_logger+ elif logging_integration == "litellm_agent":+ for callback in _in_memory_loggers:+ if isinstance(callback, LiteLLMAgentModelResolver):+ return callback++ _litellm_agent_resolver: Final = LiteLLMAgentModelResolver()+ _in_memory_loggers.append(_litellm_agent_resolver)+ return _litellm_agent_resolver+ elif logging_integration == "prometheus":+ PrometheusLogger: Final = _get_cached_prometheus_logger()++ for callback in _in_memory_loggers:+ if isinstance(callback, PrometheusLogger):+ return callback++ _prometheus_logger: Final = PrometheusLogger()+ _in_memory_loggers.append(_prometheus_logger)+ return _prometheus_logger+ elif logging_integration == "datadog":+ # Check if team-scoped credentials are provided+ _dd_api_key: Final = custom_logger_init_args_value.get("dd_api_key")+ _dd_site: Final = custom_logger_init_args_value.get("dd_site")+ _dd_agent_host: Final = custom_logger_init_args_value.get("dd_agent_host")+ _dd_agent_port: Final = custom_logger_init_args_value.get("dd_agent_port")++ if _dd_api_key or _dd_site or _dd_agent_host:+ # Team-scoped credentials: use DynamicLoggingCache for per-credential isolation+ from litellm.integrations.datadog.datadog_team_handler import (+ DataDogHandler,)- arize_config: Final = ArizeLogger.get_arize_config()- if arize_config.endpoint is None:- raise ValueError(- "No valid endpoint found for Arize, please set 'ARIZE_ENDPOINT' to your GRPC endpoint or 'ARIZE_HTTP_ENDPOINT' to your HTTP endpoint"- )- otel_config = OpenTelemetryConfig(- exporter=arize_config.protocol,- endpoint=arize_config.endpoint,- service_name=arize_config.project_name,+ return DataDogHandler.get_datadog_logger_for_request(+ standard_callback_dynamic_params=cast( # cast-ok: callback options come from dynamic config+ StandardCallbackDynamicParams, custom_logger_init_args_value+ ),+ in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,)- os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (- f"space_id={arize_config.space_key or arize_config.space_id},api_key={arize_config.api_key}"- )- for callback in _in_memory_loggers:- if isinstance(callback, ArizeLogger) and callback.callback_name == "arize":- return callback- _arize_otel_logger: Final = ArizeLogger(config=otel_config, callback_name="arize")- _in_memory_loggers.append(_arize_otel_logger)- return _arize_otel_logger- elif logging_integration == "arize_phoenix":- _v2 = _maybe_construct_otel_v2("arize_phoenix", _in_memory_loggers)- if _v2 is not None:- return _v2- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,- )+ # Global (env-var based): reuse cached instance+ for callback in _in_memory_loggers:+ if isinstance(callback, DataDogLogger):+ return callback++ _datadog_logger: Final = DataDogLogger()+ _in_memory_loggers.append(_datadog_logger)+ return _datadog_logger+ elif logging_integration == "datadog_metrics":+ for callback in _in_memory_loggers:+ if isinstance(callback, DatadogMetricsLogger):+ return callback++ _datadog_metrics_logger: Final = DatadogMetricsLogger()+ _in_memory_loggers.append(_datadog_metrics_logger)+ return _datadog_metrics_logger+ elif logging_integration == "datadog_llm_observability":+ _datadog_llm_obs_logger: Final = DataDogLLMObsLogger()+ _in_memory_loggers.append(_datadog_llm_obs_logger)+ return _datadog_llm_obs_logger+ elif logging_integration == "azure_sentinel":+ for callback in _in_memory_loggers:+ if isinstance(callback, AzureSentinelLogger):+ return callback++ _azure_sentinel_logger: Final = AzureSentinelLogger()+ _in_memory_loggers.append(_azure_sentinel_logger)+ return _azure_sentinel_logger+ elif logging_integration == "gcs_bucket":+ for callback in _in_memory_loggers:+ if isinstance(callback, GCSBucketLogger):+ return callback++ _gcs_bucket_logger: Final = GCSBucketLogger()+ _in_memory_loggers.append(_gcs_bucket_logger)+ return _gcs_bucket_logger+ elif logging_integration == "s3_v2":+ for callback in _in_memory_loggers:+ if isinstance(callback, S3V2Logger):+ return callback++ _s3_v2_logger: Final = S3V2Logger()+ _in_memory_loggers.append(_s3_v2_logger)+ return _s3_v2_logger+ elif logging_integration == "clickhouse":+ for callback in _in_memory_loggers:+ if isinstance(callback, ClickHouseSpendLogger):+ return callback++ _clickhouse_spend_logger: Final = ClickHouseSpendLogger()+ _in_memory_loggers.append(_clickhouse_spend_logger)+ return _clickhouse_spend_logger+ elif logging_integration == "pointfive":+ for callback in _in_memory_loggers:+ if isinstance(callback, PointFiveLogger):+ return callback++ _pointfive_logger: Final = PointFiveLogger()+ _in_memory_loggers.append(_pointfive_logger)+ return _pointfive_logger+ elif logging_integration == "zerobus":+ for callback in _in_memory_loggers:+ if isinstance(callback, ZerobusLogger):+ return callback++ _zerobus_logger: Final = ZerobusLogger()+ _in_memory_loggers.append(_zerobus_logger)+ return _zerobus_logger+ elif logging_integration == "aws_sqs":+ for callback in _in_memory_loggers:+ if isinstance(callback, SQSLogger):+ return callback++ _aws_sqs_logger: Final = SQSLogger()+ _in_memory_loggers.append(_aws_sqs_logger)+ return _aws_sqs_logger+ elif logging_integration == "azure_storage":+ for callback in _in_memory_loggers:+ if isinstance(callback, AzureBlobStorageLogger):+ return callback++ _azure_storage_logger: Final = AzureBlobStorageLogger()+ _in_memory_loggers.append(_azure_storage_logger)+ return _azure_storage_logger+ elif logging_integration == "opik":+ for callback in _in_memory_loggers:+ if isinstance(callback, OpikLogger):+ return callback++ _opik_logger: Final = OpikLogger()+ _in_memory_loggers.append(_opik_logger)+ return _opik_logger+ elif logging_integration == "arize":+ _v2 = _maybe_construct_otel_v2("arize", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- arize_phoenix_config: Final = ArizePhoenixLogger.get_arize_phoenix_config()- otel_config = OpenTelemetryConfig(- exporter=arize_phoenix_config.protocol,- endpoint=arize_phoenix_config.endpoint,- headers=arize_phoenix_config.otlp_auth_headers,+ arize_config: Final = ArizeLogger.get_arize_config()+ if arize_config.endpoint is None:+ raise ValueError(+ "No valid endpoint found for Arize, please set 'ARIZE_ENDPOINT' to your GRPC endpoint or 'ARIZE_HTTP_ENDPOINT' to your HTTP endpoint")+ otel_config = OpenTelemetryConfig(+ exporter=arize_config.protocol,+ endpoint=arize_config.endpoint,+ service_name=arize_config.project_name,+ )- # auth can be disabled on local deployments of arize phoenix- if arize_phoenix_config.otlp_auth_headers is not None:- os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = arize_phoenix_config.otlp_auth_headers-- for callback in _in_memory_loggers:- if isinstance(callback, ArizePhoenixLogger) and callback.callback_name == "arize_phoenix":- return callback- _arize_phoenix_otel_logger: Final = ArizePhoenixLogger(config=otel_config, callback_name="arize_phoenix")- _in_memory_loggers.append(_arize_phoenix_otel_logger)- return _arize_phoenix_otel_logger- elif logging_integration == "levo":- _v2 = _maybe_construct_otel_v2("levo", _in_memory_loggers)- if _v2 is not None:- return _v2- from litellm.integrations.levo.levo import LevoLogger- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,- )+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (+ f"space_id={arize_config.space_key or arize_config.space_id},api_key={arize_config.api_key}"+ )+ for callback in _in_memory_loggers:+ if isinstance(callback, ArizeLogger) and callback.callback_name == "arize":+ return callback+ _arize_otel_logger: Final = ArizeLogger(config=otel_config, callback_name="arize")+ _in_memory_loggers.append(_arize_otel_logger)+ return _arize_otel_logger+ elif logging_integration == "arize_phoenix":+ _v2 = _maybe_construct_otel_v2("arize_phoenix", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- levo_config: Final = LevoLogger.get_levo_config()- otel_config = OpenTelemetryConfig(- exporter=levo_config.protocol,- endpoint=levo_config.endpoint,- headers=levo_config.otlp_auth_headers,- )+ arize_phoenix_config: Final = ArizePhoenixLogger.get_arize_phoenix_config()+ otel_config = OpenTelemetryConfig(+ exporter=arize_phoenix_config.protocol,+ endpoint=arize_phoenix_config.endpoint,+ headers=arize_phoenix_config.otlp_auth_headers,+ )- # Check if LevoLogger instance already exists- for callback in _in_memory_loggers:- if isinstance(callback, LevoLogger) and callback.callback_name == "levo":- return callback+ # auth can be disabled on local deployments of arize phoenix+ if arize_phoenix_config.otlp_auth_headers is not None:+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = arize_phoenix_config.otlp_auth_headers++ for callback in _in_memory_loggers:+ if isinstance(callback, ArizePhoenixLogger) and callback.callback_name == "arize_phoenix":+ return callback+ _arize_phoenix_otel_logger: Final = ArizePhoenixLogger(config=otel_config, callback_name="arize_phoenix")+ _in_memory_loggers.append(_arize_phoenix_otel_logger)+ return _arize_phoenix_otel_logger+ elif logging_integration == "levo":+ _v2 = _maybe_construct_otel_v2("levo", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ from litellm.integrations.levo.levo import LevoLogger+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- _levo_otel_logger: Final = LevoLogger(config=otel_config, callback_name="levo")- _in_memory_loggers.append(_levo_otel_logger)- return _levo_otel_logger- elif logging_integration == "otel":- # Gate the new typed V2 adapter behind LITELLM_OTEL_V2. When off,- # the legacy 3,227-line god-class is used unchanged. The two are- # never registered simultaneously — the dedup loop below treats- # any module under ``litellm.integrations.otel`` or- # ``litellm.integrations.opentelemetry`` as "the OTel callback".- from litellm.integrations.otel.model.config import is_otel_v2_enabled-- if is_otel_v2_enabled():- from litellm.integrations.otel.logger import OpenTelemetryV2, build_otel_v2_logger- from litellm.integrations.otel.model.config import OpenTelemetryV2Config-- for callback in _in_memory_loggers:- if isinstance(callback, OpenTelemetryV2):- return callback- otel_settings: Final = _get_custom_logger_settings_from_proxy_server(callback_name=logging_integration)- otel_logger_v2: Final = build_otel_v2_logger(- config=OpenTelemetryV2Config(**otel_settings), settings=otel_settings- )- _in_memory_loggers.append(otel_logger_v2)- _maybe_auto_initialize_arize_phoenix(_in_memory_loggers)- return otel_logger_v2+ levo_config: Final = LevoLogger.get_levo_config()+ otel_config = OpenTelemetryConfig(+ exporter=levo_config.protocol,+ endpoint=levo_config.endpoint,+ headers=levo_config.otlp_auth_headers,+ )- from litellm.integrations.opentelemetry import OpenTelemetry+ # Check if LevoLogger instance already exists+ for callback in _in_memory_loggers:+ if isinstance(callback, LevoLogger) and callback.callback_name == "levo":+ return callback++ _levo_otel_logger: Final = LevoLogger(config=otel_config, callback_name="levo")+ _in_memory_loggers.append(_levo_otel_logger)+ return _levo_otel_logger+ elif logging_integration == "otel":+ # Gate the new typed V2 adapter behind LITELLM_OTEL_V2. When off,+ # the legacy 3,227-line god-class is used unchanged. The two are+ # never registered simultaneously — the dedup loop below treats+ # any module under ``litellm.integrations.otel`` or+ # ``litellm.integrations.opentelemetry`` as "the OTel callback".+ from litellm.integrations.otel.model.config import is_otel_v2_enabled++ if is_otel_v2_enabled():+ from litellm.integrations.otel.logger import OpenTelemetryV2, build_otel_v2_logger+ from litellm.integrations.otel.model.config import OpenTelemetryV2Configfor callback in _in_memory_loggers:- if type(callback) is OpenTelemetry:+ if isinstance(callback, OpenTelemetryV2):return callback- otel_logger: Final = OpenTelemetry(- **_get_custom_logger_settings_from_proxy_server(callback_name=logging_integration)+ otel_settings: Final = _get_custom_logger_settings_from_proxy_server(callback_name=logging_integration)+ otel_logger_v2: Final = build_otel_v2_logger(+ config=OpenTelemetryV2Config(**otel_settings), settings=otel_settings)- _in_memory_loggers.append(otel_logger)-- # Auto-initialize Arize Phoenix if Phoenix env vars are configured- # This allows users to get nested traces in both OTEL and Phoenix- # by only specifying "otel" in callbacks+ _in_memory_loggers.append(otel_logger_v2)_maybe_auto_initialize_arize_phoenix(_in_memory_loggers)+ return otel_logger_v2- return otel_logger+ from litellm.integrations.opentelemetry import OpenTelemetry- elif logging_integration == "galileo":- for callback in _in_memory_loggers:- if isinstance(callback, GalileoObserve):- return callback-- galileo_logger: Final = GalileoObserve()- _in_memory_loggers.append(galileo_logger)- return galileo_logger- elif logging_integration == "cloudzero":- from litellm.integrations.cloudzero.cloudzero import CloudZeroLogger-- for callback in _in_memory_loggers:- if isinstance(callback, CloudZeroLogger):- return callback- cloudzero_logger: Final = CloudZeroLogger()- _in_memory_loggers.append(cloudzero_logger)- return cloudzero_logger- elif logging_integration == "focus":- from litellm.integrations.focus.focus_logger import FocusLogger-- for callback in _in_memory_loggers:- if type(callback) is FocusLogger: # exact match; exclude subclasses like VantageLogger- return callback- focus_logger: Final = FocusLogger()- _in_memory_loggers.append(focus_logger)- return focus_logger- elif logging_integration == "mavvrik":- from litellm.integrations.mavvrik_focus.mavvrik_focus_logger import (- MavvrikFocusLogger,- )-- for callback in _in_memory_loggers:- if type(callback) is MavvrikFocusLogger:- return callback- mavvrik_focus_logger: Final = MavvrikFocusLogger()- _in_memory_loggers.append(mavvrik_focus_logger)- return mavvrik_focus_logger- elif logging_integration == "vantage":- from litellm.integrations.vantage.vantage_logger import VantageLogger-- for callback in _in_memory_loggers:- if isinstance(callback, VantageLogger):- return callback- vantage_logger: Final = VantageLogger()- _in_memory_loggers.append(vantage_logger)- return vantage_logger- elif logging_integration == "ternary":- from litellm.integrations.ternary.ternary_logger import TernaryLogger-- for callback in _in_memory_loggers:- if isinstance(callback, TernaryLogger):- return callback- ternary_logger: Final = TernaryLogger()- _in_memory_loggers.append(ternary_logger)- return ternary_logger- elif logging_integration == "deepeval":- for callback in _in_memory_loggers:- if isinstance(callback, DeepEvalLogger):- return callback- deepeval_logger: Final = DeepEvalLogger()- _in_memory_loggers.append(deepeval_logger)- return deepeval_logger-- elif logging_integration == "logfire":- if "LOGFIRE_TOKEN" not in os.environ:- raise ValueError("LOGFIRE_TOKEN not found in environment variables")- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,- )-- logfire_base_url: Final = os.getenv("LOGFIRE_BASE_URL", "https://logfire-api.pydantic.dev")- otel_config = OpenTelemetryConfig(- exporter="otlp_http",- endpoint=f"{logfire_base_url.rstrip('/')}/v1/traces",- headers=f"Authorization={os.getenv('LOGFIRE_TOKEN')}",- )- for callback in _in_memory_loggers:- # Use exact type check to avoid matching ArizePhoenixLogger (subclass)- if type(callback) is OpenTelemetry:- return callback- _otel_logger = OpenTelemetry(config=otel_config)- _in_memory_loggers.append(_otel_logger)- return _otel_logger- elif logging_integration == "dynamic_rate_limiter":- from litellm.proxy.hooks.dynamic_rate_limiter import (- PROXY_DynamicRateLimitHandler,- )-- for callback in _in_memory_loggers:- if isinstance(callback, PROXY_DynamicRateLimitHandler):- return callback-- if internal_usage_cache is None:- raise Exception(f"Internal Error: Cache cannot be empty - internal_usage_cache={internal_usage_cache}")-- dynamic_rate_limiter_obj: Final = PROXY_DynamicRateLimitHandler(internal_usage_cache=internal_usage_cache)-- if llm_router is not None and isinstance(llm_router, litellm.Router):- dynamic_rate_limiter_obj.update_variables(llm_router=llm_router)- _in_memory_loggers.append(dynamic_rate_limiter_obj)- return dynamic_rate_limiter_obj- elif logging_integration == "dynamic_rate_limiter_v3":- from litellm.proxy.hooks.dynamic_rate_limiter_v3 import (- PROXY_DynamicRateLimitHandlerV3,- )-- for callback in _in_memory_loggers:- if isinstance(callback, PROXY_DynamicRateLimitHandlerV3):- return callback-- if internal_usage_cache is None:- raise Exception(f"Internal Error: Cache cannot be empty - internal_usage_cache={internal_usage_cache}")-- dynamic_rate_limiter_obj_v3: Final = PROXY_DynamicRateLimitHandlerV3(- internal_usage_cache=internal_usage_cache- )+ for callback in _in_memory_loggers:+ if type(callback) is OpenTelemetry:+ return callback+ otel_logger: Final = OpenTelemetry(+ **_get_custom_logger_settings_from_proxy_server(callback_name=logging_integration)+ )+ _in_memory_loggers.append(otel_logger)++ # Auto-initialize Arize Phoenix if Phoenix env vars are configured+ # This allows users to get nested traces in both OTEL and Phoenix+ # by only specifying "otel" in callbacks+ _maybe_auto_initialize_arize_phoenix(_in_memory_loggers)++ return otel_logger++ elif logging_integration == "galileo":+ for callback in _in_memory_loggers:+ if isinstance(callback, GalileoObserve):+ return callback++ galileo_logger: Final = GalileoObserve()+ _in_memory_loggers.append(galileo_logger)+ return galileo_logger+ elif logging_integration == "cloudzero":+ from litellm.integrations.cloudzero.cloudzero import CloudZeroLogger++ for callback in _in_memory_loggers:+ if isinstance(callback, CloudZeroLogger):+ return callback+ cloudzero_logger: Final = CloudZeroLogger()+ _in_memory_loggers.append(cloudzero_logger)+ return cloudzero_logger+ elif logging_integration == "focus":+ from litellm.integrations.focus.focus_logger import FocusLogger++ for callback in _in_memory_loggers:+ if type(callback) is FocusLogger: # exact match; exclude subclasses like VantageLogger+ return callback+ focus_logger: Final = FocusLogger()+ _in_memory_loggers.append(focus_logger)+ return focus_logger+ elif logging_integration == "mavvrik":+ from litellm.integrations.mavvrik_focus.mavvrik_focus_logger import (+ MavvrikFocusLogger,+ )- if llm_router is not None and isinstance(llm_router, litellm.Router):- dynamic_rate_limiter_obj_v3.update_variables(llm_router=llm_router)- _in_memory_loggers.append(dynamic_rate_limiter_obj_v3)- return dynamic_rate_limiter_obj_v3- elif logging_integration == "langtrace":- if "LANGTRACE_API_KEY" not in os.environ:- raise ValueError("LANGTRACE_API_KEY not found in environment variables")- _v2 = _maybe_construct_otel_v2("langtrace", _in_memory_loggers)- if _v2 is not None:- return _v2+ for callback in _in_memory_loggers:+ if type(callback) is MavvrikFocusLogger:+ return callback+ mavvrik_focus_logger: Final = MavvrikFocusLogger()+ _in_memory_loggers.append(mavvrik_focus_logger)+ return mavvrik_focus_logger+ elif logging_integration == "vantage":+ from litellm.integrations.vantage.vantage_logger import VantageLogger++ for callback in _in_memory_loggers:+ if isinstance(callback, VantageLogger):+ return callback+ vantage_logger: Final = VantageLogger()+ _in_memory_loggers.append(vantage_logger)+ return vantage_logger+ elif logging_integration == "ternary":+ from litellm.integrations.ternary.ternary_logger import TernaryLogger++ for callback in _in_memory_loggers:+ if isinstance(callback, TernaryLogger):+ return callback+ ternary_logger: Final = TernaryLogger()+ _in_memory_loggers.append(ternary_logger)+ return ternary_logger+ elif logging_integration == "deepeval":+ for callback in _in_memory_loggers:+ if isinstance(callback, DeepEvalLogger):+ return callback+ deepeval_logger: Final = DeepEvalLogger()+ _in_memory_loggers.append(deepeval_logger)+ return deepeval_logger++ elif logging_integration == "logfire":+ if "LOGFIRE_TOKEN" not in os.environ:+ raise ValueError("LOGFIRE_TOKEN not found in environment variables")+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,- )+ logfire_base_url: Final = os.getenv("LOGFIRE_BASE_URL", "https://logfire-api.pydantic.dev")+ otel_config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint=f"{logfire_base_url.rstrip('/')}/v1/traces",+ headers=f"Authorization={os.getenv('LOGFIRE_TOKEN')}",+ )+ for callback in _in_memory_loggers:+ # Use exact type check to avoid matching ArizePhoenixLogger (subclass)+ if type(callback) is OpenTelemetry:+ return callback+ _otel_logger = OpenTelemetry(config=otel_config)+ _in_memory_loggers.append(_otel_logger)+ return _otel_logger+ elif logging_integration == "dynamic_rate_limiter":+ from litellm.proxy.hooks.dynamic_rate_limiter import (+ PROXY_DynamicRateLimitHandler,+ )- otel_config = OpenTelemetryConfig(- exporter="otlp_http",- endpoint=langtrace_trace_endpoint(os.getenv("LANGTRACE_API_HOST")),- headers=f"x-api-key={os.environ['LANGTRACE_API_KEY']}",- )- for callback in _in_memory_loggers:- if isinstance(callback, OpenTelemetry) and callback.callback_name == "langtrace":- return callback- _otel_logger = OpenTelemetry(config=otel_config, callback_name="langtrace")- _in_memory_loggers.append(_otel_logger)- return _otel_logger+ for callback in _in_memory_loggers:+ if isinstance(callback, PROXY_DynamicRateLimitHandler):+ return callback- elif logging_integration == "signoz":- from litellm.integrations.otel.presets.signoz import (- SIGNOZ_INGESTION_ENDPOINT_ENV,- )+ if internal_usage_cache is None:+ raise Exception(f"Internal Error: Cache cannot be empty - internal_usage_cache={internal_usage_cache}")- _signoz_endpoint: Final = os.getenv(SIGNOZ_INGESTION_ENDPOINT_ENV)- if not _signoz_endpoint:- raise ValueError(f"{SIGNOZ_INGESTION_ENDPOINT_ENV} not found in environment variables")+ dynamic_rate_limiter_obj: Final = PROXY_DynamicRateLimitHandler(internal_usage_cache=internal_usage_cache)- _signoz_v2: Final = _maybe_construct_otel_v2("signoz", _in_memory_loggers)- if _signoz_v2 is not None:- return _signoz_v2+ if llm_router is not None and isinstance(llm_router, litellm.Router):+ dynamic_rate_limiter_obj.update_variables(llm_router=llm_router)+ _in_memory_loggers.append(dynamic_rate_limiter_obj)+ return dynamic_rate_limiter_obj+ elif logging_integration == "dynamic_rate_limiter_v3":+ from litellm.proxy.hooks.dynamic_rate_limiter_v3 import (+ PROXY_DynamicRateLimitHandlerV3,+ )- from litellm.integrations.opentelemetry import (- OpenTelemetry,- OpenTelemetryConfig,- )+ for callback in _in_memory_loggers:+ if isinstance(callback, PROXY_DynamicRateLimitHandlerV3):+ return callback++ if internal_usage_cache is None:+ raise Exception(f"Internal Error: Cache cannot be empty - internal_usage_cache={internal_usage_cache}")++ dynamic_rate_limiter_obj_v3: Final = PROXY_DynamicRateLimitHandlerV3(internal_usage_cache=internal_usage_cache)++ if llm_router is not None and isinstance(llm_router, litellm.Router):+ dynamic_rate_limiter_obj_v3.update_variables(llm_router=llm_router)+ _in_memory_loggers.append(dynamic_rate_limiter_obj_v3)+ return dynamic_rate_limiter_obj_v3+ elif logging_integration == "langtrace":+ if "LANGTRACE_API_KEY" not in os.environ:+ raise ValueError("LANGTRACE_API_KEY not found in environment variables")+ _v2 = _maybe_construct_otel_v2("langtrace", _in_memory_loggers)+ if _v2 is not None:+ return _v2++ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- _signoz_base: Final = _signoz_endpoint.rstrip("/")- _signoz_key: Final = os.getenv("SIGNOZ_INGESTION_KEY")- _signoz_config: Final = OpenTelemetryConfig(- exporter="otlp_http",- endpoint=(_signoz_base if _signoz_base.endswith("/v1/traces") else f"{_signoz_base}/v1/traces"),- headers=(f"signoz-ingestion-key={_signoz_key}" if _signoz_key else None),- )- for callback in _in_memory_loggers:- if isinstance(callback, OpenTelemetry) and callback.callback_name == "signoz":- return callback- _signoz_logger: Final = OpenTelemetry(config=_signoz_config, callback_name="signoz")- _in_memory_loggers.append(_signoz_logger)- return _signoz_logger+ otel_config = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint=langtrace_trace_endpoint(os.getenv("LANGTRACE_API_HOST")),+ headers=f"x-api-key={os.environ['LANGTRACE_API_KEY']}",+ )+ for callback in _in_memory_loggers:+ if isinstance(callback, OpenTelemetry) and callback.callback_name == "langtrace":+ return callback+ _otel_logger = OpenTelemetry(config=otel_config, callback_name="langtrace")+ _in_memory_loggers.append(_otel_logger)+ return _otel_logger++ elif logging_integration == "signoz":+ from litellm.integrations.otel.presets.signoz import (+ SIGNOZ_INGESTION_ENDPOINT_ENV,+ )- elif logging_integration == "mlflow":- for callback in _in_memory_loggers:- if isinstance(callback, MlflowLogger):- return callback+ _signoz_endpoint: Final = os.getenv(SIGNOZ_INGESTION_ENDPOINT_ENV)+ if not _signoz_endpoint:+ raise ValueError(f"{SIGNOZ_INGESTION_ENDPOINT_ENV} not found in environment variables")- _mlflow_logger: Final = MlflowLogger()- _in_memory_loggers.append(_mlflow_logger)- return _mlflow_logger- elif logging_integration == "langfuse":- for callback in _in_memory_loggers:- if isinstance(callback, LangfusePromptManagement):- return callback+ _signoz_v2: Final = _maybe_construct_otel_v2("signoz", _in_memory_loggers)+ if _signoz_v2 is not None:+ return _signoz_v2- langfuse_logger: Final = LangfusePromptManagement()- _in_memory_loggers.append(langfuse_logger)- return langfuse_logger- elif logging_integration == "langfuse_otel":- _v2 = _maybe_construct_otel_v2("langfuse_otel", _in_memory_loggers)- if _v2 is not None:- return _v2- from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )- for callback in _in_memory_loggers:- if isinstance(callback, LangfuseOtelLogger) and callback.callback_name == "langfuse_otel":- return callback- # Allow LangfuseOtelLogger to initialize its own config safely- # This prevents startup crashes if LANGFUSE keys are not in env (e.g. for dynamic usage)- _otel_logger = LangfuseOtelLogger(config=None, callback_name="langfuse_otel")- _in_memory_loggers.append(_otel_logger)- return _otel_logger- elif logging_integration == "weave_otel":- _v2 = _maybe_construct_otel_v2("weave_otel", _in_memory_loggers)- if _v2 is not None:- return _v2- from litellm.integrations.opentelemetry import OpenTelemetryConfig- from litellm.integrations.weave.weave_otel import (- WeaveOtelLogger,- get_weave_otel_config,- )+ _signoz_base: Final = _signoz_endpoint.rstrip("/")+ _signoz_key: Final = os.getenv("SIGNOZ_INGESTION_KEY")+ _signoz_config: Final = OpenTelemetryConfig(+ exporter="otlp_http",+ endpoint=(_signoz_base if _signoz_base.endswith("/v1/traces") else f"{_signoz_base}/v1/traces"),+ headers=(f"signoz-ingestion-key={_signoz_key}" if _signoz_key else None),+ )+ for callback in _in_memory_loggers:+ if isinstance(callback, OpenTelemetry) and callback.callback_name == "signoz":+ return callback+ _signoz_logger: Final = OpenTelemetry(config=_signoz_config, callback_name="signoz")+ _in_memory_loggers.append(_signoz_logger)+ return _signoz_logger++ elif logging_integration == "mlflow":+ for callback in _in_memory_loggers:+ if isinstance(callback, MlflowLogger):+ return callback++ _mlflow_logger: Final = MlflowLogger()+ _in_memory_loggers.append(_mlflow_logger)+ return _mlflow_logger+ elif logging_integration == "langfuse":+ for callback in _in_memory_loggers:+ if isinstance(callback, LangfusePromptManagement):+ return callback++ langfuse_logger: Final = LangfusePromptManagement()+ _in_memory_loggers.append(langfuse_logger)+ return langfuse_logger+ elif logging_integration == "langfuse_otel":+ _v2 = _maybe_construct_otel_v2("langfuse_otel", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger++ for callback in _in_memory_loggers:+ if isinstance(callback, LangfuseOtelLogger) and callback.callback_name == "langfuse_otel":+ return callback+ # Allow LangfuseOtelLogger to initialize its own config safely+ # This prevents startup crashes if LANGFUSE keys are not in env (e.g. for dynamic usage)+ _otel_logger = LangfuseOtelLogger(config=None, callback_name="langfuse_otel")+ _in_memory_loggers.append(_otel_logger)+ return _otel_logger+ elif logging_integration == "weave_otel":+ _v2 = _maybe_construct_otel_v2("weave_otel", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ from litellm.integrations.opentelemetry import OpenTelemetryConfig+ from litellm.integrations.weave.weave_otel import (+ WeaveOtelLogger,+ get_weave_otel_config,+ )- weave_otel_config: Final = get_weave_otel_config()+ weave_otel_config: Final = get_weave_otel_config()- otel_config = OpenTelemetryConfig(- exporter=weave_otel_config.protocol,- endpoint=weave_otel_config.endpoint,- headers=weave_otel_config.otlp_auth_headers,- )+ otel_config = OpenTelemetryConfig(+ exporter=weave_otel_config.protocol,+ endpoint=weave_otel_config.endpoint,+ headers=weave_otel_config.otlp_auth_headers,+ )- for callback in _in_memory_loggers:- if isinstance(callback, WeaveOtelLogger) and callback.callback_name == "weave_otel":- return callback- _otel_logger = WeaveOtelLogger(config=otel_config, callback_name="weave_otel")- _in_memory_loggers.append(_otel_logger)- return _otel_logger- elif logging_integration == "pagerduty":- pagerduty_loggers: Final = _enterprise_alerting_loggers()- for callback in _in_memory_loggers:- if isinstance(callback, pagerduty_loggers.pagerduty):- return callback- pagerduty_logger: Final = pagerduty_loggers.pagerduty(**custom_logger_init_args_value)- _in_memory_loggers.append(pagerduty_logger)- return pagerduty_logger- elif logging_integration == "anthropic_cache_control_hook":- for callback in _in_memory_loggers:- if isinstance(callback, AnthropicCacheControlHook):- return callback- anthropic_cache_control_hook: Final = AnthropicCacheControlHook()- _in_memory_loggers.append(anthropic_cache_control_hook)- return anthropic_cache_control_hook- elif logging_integration == "vector_store_pre_call_hook":- from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (- VectorStorePreCallHook,- )+ for callback in _in_memory_loggers:+ if isinstance(callback, WeaveOtelLogger) and callback.callback_name == "weave_otel":+ return callback+ _otel_logger = WeaveOtelLogger(config=otel_config, callback_name="weave_otel")+ _in_memory_loggers.append(_otel_logger)+ return _otel_logger+ elif logging_integration == "pagerduty":+ pagerduty_loggers: Final = _enterprise_alerting_loggers()+ for callback in _in_memory_loggers:+ if isinstance(callback, pagerduty_loggers.pagerduty):+ return callback+ pagerduty_logger: Final = pagerduty_loggers.pagerduty(**custom_logger_init_args_value)+ _in_memory_loggers.append(pagerduty_logger)+ return pagerduty_logger+ elif logging_integration == "anthropic_cache_control_hook":+ for callback in _in_memory_loggers:+ if isinstance(callback, AnthropicCacheControlHook):+ return callback+ anthropic_cache_control_hook: Final = AnthropicCacheControlHook()+ _in_memory_loggers.append(anthropic_cache_control_hook)+ return anthropic_cache_control_hook+ elif logging_integration == "vector_store_pre_call_hook":+ from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (+ VectorStorePreCallHook,+ )- for callback in _in_memory_loggers:- if isinstance(callback, VectorStorePreCallHook):- return callback- vector_store_pre_call_hook: Final = VectorStorePreCallHook()- _in_memory_loggers.append(vector_store_pre_call_hook)- return vector_store_pre_call_hook- elif logging_integration == "gcs_pubsub":- for callback in _in_memory_loggers:- if isinstance(callback, GcsPubSubLogger):- return callback- _gcs_pubsub_logger: Final = GcsPubSubLogger()- _in_memory_loggers.append(_gcs_pubsub_logger)- return _gcs_pubsub_logger- elif logging_integration == "generic_api":- for callback in _in_memory_loggers:- if isinstance(callback, _GENERIC_API_LOGGER_CLS):- return callback- generic_api_logger: Final = GenericAPILogger()- _in_memory_loggers.append(generic_api_logger)- return generic_api_logger- elif logging_integration == "resend_email":- resend_email_loggers: Final = _enterprise_alerting_loggers()- for callback in _in_memory_loggers:- if isinstance(callback, resend_email_loggers.resend_email):- return callback- resend_email_logger: Final = resend_email_loggers.resend_email()- _in_memory_loggers.append(resend_email_logger)- return resend_email_logger- elif logging_integration == "sendgrid_email":- sendgrid_email_loggers: Final = _enterprise_alerting_loggers()- for callback in _in_memory_loggers:- if isinstance(callback, sendgrid_email_loggers.sendgrid_email):- return callback- sendgrid_email_logger: Final = sendgrid_email_loggers.sendgrid_email()- _in_memory_loggers.append(sendgrid_email_logger)- return sendgrid_email_logger- elif logging_integration == "smtp_email":- smtp_email_loggers: Final = _enterprise_alerting_loggers()- for callback in _in_memory_loggers:- if isinstance(callback, smtp_email_loggers.smtp_email):- return callback- smtp_email_logger: Final = smtp_email_loggers.smtp_email()- _in_memory_loggers.append(smtp_email_logger)- return smtp_email_logger- elif logging_integration == "humanloop":- for callback in _in_memory_loggers:- if isinstance(callback, HumanloopLogger):- return callback+ for callback in _in_memory_loggers:+ if isinstance(callback, VectorStorePreCallHook):+ return callback+ vector_store_pre_call_hook: Final = VectorStorePreCallHook()+ _in_memory_loggers.append(vector_store_pre_call_hook)+ return vector_store_pre_call_hook+ elif logging_integration == "gcs_pubsub":+ for callback in _in_memory_loggers:+ if isinstance(callback, GcsPubSubLogger):+ return callback+ _gcs_pubsub_logger: Final = GcsPubSubLogger()+ _in_memory_loggers.append(_gcs_pubsub_logger)+ return _gcs_pubsub_logger+ elif logging_integration == "generic_api":+ for callback in _in_memory_loggers:+ if isinstance(callback, _GENERIC_API_LOGGER_CLS):+ return callback+ generic_api_logger: Final = GenericAPILogger()+ _in_memory_loggers.append(generic_api_logger)+ return generic_api_logger+ elif logging_integration == "resend_email":+ resend_email_loggers: Final = _enterprise_alerting_loggers()+ for callback in _in_memory_loggers:+ if isinstance(callback, resend_email_loggers.resend_email):+ return callback+ resend_email_logger: Final = resend_email_loggers.resend_email()+ _in_memory_loggers.append(resend_email_logger)+ return resend_email_logger+ elif logging_integration == "sendgrid_email":+ sendgrid_email_loggers: Final = _enterprise_alerting_loggers()+ for callback in _in_memory_loggers:+ if isinstance(callback, sendgrid_email_loggers.sendgrid_email):+ return callback+ sendgrid_email_logger: Final = sendgrid_email_loggers.sendgrid_email()+ _in_memory_loggers.append(sendgrid_email_logger)+ return sendgrid_email_logger+ elif logging_integration == "smtp_email":+ smtp_email_loggers: Final = _enterprise_alerting_loggers()+ for callback in _in_memory_loggers:+ if isinstance(callback, smtp_email_loggers.smtp_email):+ return callback+ smtp_email_logger: Final = smtp_email_loggers.smtp_email()+ _in_memory_loggers.append(smtp_email_logger)+ return smtp_email_logger+ elif logging_integration == "humanloop":+ for callback in _in_memory_loggers:+ if isinstance(callback, HumanloopLogger):+ return callback++ humanloop_logger: Final = HumanloopLogger()+ _in_memory_loggers.append(humanloop_logger)+ return humanloop_logger+ elif logging_integration == "dotprompt":+ for callback in _in_memory_loggers:+ if isinstance(callback, DotpromptManager):+ return callback++ dotprompt_logger: Final = DotpromptManager()+ _in_memory_loggers.append(dotprompt_logger)+ return dotprompt_logger+ elif logging_integration == "bitbucket":+ from litellm.integrations.bitbucket.bitbucket_prompt_manager import (+ BitBucketPromptManager,+ )- humanloop_logger: Final = HumanloopLogger()- _in_memory_loggers.append(humanloop_logger)- return humanloop_logger- elif logging_integration == "dotprompt":- for callback in _in_memory_loggers:- if isinstance(callback, DotpromptManager):- return callback+ for callback in _in_memory_loggers:+ if isinstance(callback, BitBucketPromptManager):+ return callback++ # Get global BitBucket config+ bitbucket_config: Final = getattr(litellm, "global_bitbucket_config", None)+ if bitbucket_config is None:+ raise ValueError("BitBucket configuration not found. Please set litellm.global_bitbucket_config first.")++ bitbucket_logger: Final = BitBucketPromptManager(bitbucket_config=bitbucket_config)+ _in_memory_loggers.append(bitbucket_logger)+ return bitbucket_logger+ elif logging_integration == "gitlab":+ from litellm.integrations.gitlab.gitlab_prompt_manager import (+ GitLabPromptManager,+ )- dotprompt_logger: Final = DotpromptManager()- _in_memory_loggers.append(dotprompt_logger)- return dotprompt_logger- elif logging_integration == "bitbucket":- from litellm.integrations.bitbucket.bitbucket_prompt_manager import (- BitBucketPromptManager,+ for callback in _in_memory_loggers:+ if isinstance(callback, GitLabPromptManager):+ return callback++ # Get global BitBucket config+ gitlab_config: Final = getattr(litellm, "global_gitlab_config", None)+ if gitlab_config is None:+ raise ValueError("Gitlab configuration not found. Please set litellm.global_gitlab_config first.")++ gitlab_logger: Final = GitLabPromptManager(gitlab_config=gitlab_config)+ _in_memory_loggers.append(gitlab_logger)+ return gitlab_logger+ elif logging_integration == "newrelic":+ if custom_logger_init_args_value.get("newrelic_api_key"):+ # Team-scoped credentials: per-team METRICS logger, isolated per+ # credential set via DynamicLoggingCache. The trace logger for+ # this name stays on the global path below.+ from litellm.integrations.newrelic.newrelic_team_handler import (+ NewRelicHandler,)- for callback in _in_memory_loggers:- if isinstance(callback, BitBucketPromptManager):- return callback-- # Get global BitBucket config- bitbucket_config: Final = getattr(litellm, "global_bitbucket_config", None)- if bitbucket_config is None:- raise ValueError("BitBucket configuration not found. Please set litellm.global_bitbucket_config first.")-- bitbucket_logger: Final = BitBucketPromptManager(bitbucket_config=bitbucket_config)- _in_memory_loggers.append(bitbucket_logger)- return bitbucket_logger- elif logging_integration == "gitlab":- from litellm.integrations.gitlab.gitlab_prompt_manager import (- GitLabPromptManager,+ return NewRelicHandler.get_newrelic_logger_for_request(+ standard_callback_dynamic_params=cast( # cast-ok: callback options come from dynamic config+ StandardCallbackDynamicParams, custom_logger_init_args_value+ ),+ in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,)- for callback in _in_memory_loggers:- if isinstance(callback, GitLabPromptManager):- return callback-- # Get global BitBucket config- gitlab_config: Final = getattr(litellm, "global_gitlab_config", None)- if gitlab_config is None:- raise ValueError("Gitlab configuration not found. Please set litellm.global_gitlab_config first.")-- gitlab_logger: Final = GitLabPromptManager(gitlab_config=gitlab_config)- _in_memory_loggers.append(gitlab_logger)- return gitlab_logger- elif logging_integration == "newrelic":- if custom_logger_init_args_value.get("newrelic_api_key"):- # Team-scoped credentials: per-team METRICS logger, isolated per- # credential set via DynamicLoggingCache. The trace logger for- # this name stays on the global path below.- from litellm.integrations.newrelic.newrelic_team_handler import (- NewRelicHandler,- )+ _v2 = _maybe_construct_otel_v2("newrelic", _in_memory_loggers)+ if _v2 is not None:+ return _v2+ for callback in _in_memory_loggers:+ if isinstance(callback, NewRelicLogger):+ return callback+ newrelic_logger: Final = NewRelicLogger()+ _in_memory_loggers.append(newrelic_logger)+ return newrelic_logger+ return None- return NewRelicHandler.get_newrelic_logger_for_request(- standard_callback_dynamic_params=cast( # cast-ok: callback options come from dynamic config- StandardCallbackDynamicParams, custom_logger_init_args_value- ),- in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache,- )- _v2 = _maybe_construct_otel_v2("newrelic", _in_memory_loggers)- if _v2 is not None:- return _v2- for callback in _in_memory_loggers:- if isinstance(callback, NewRelicLogger):- return callback- newrelic_logger: Final = NewRelicLogger()- _in_memory_loggers.append(newrelic_logger)- return newrelic_logger- return None+def _init_custom_logger_compatible_class(+ logging_integration: str,+ internal_usage_cache: DualCache | None,+ llm_router: object,+ custom_logger_init_args: dict[str, object] | None = {},+ raise_import_errors: bool = False,+) -> CustomLogger | None:+ """+ Initialize a custom logger compatible class+ """+ try:+ return build_custom_logger_compatible_class(+ logging_integration,+ internal_usage_cache=internal_usage_cache,+ llm_router=llm_router,+ custom_logger_init_args=custom_logger_init_args,+ )except Exception as e:+ if raise_import_errors and isinstance(e, ImportError):+ raise ImportError(+ f"Could not build the '{logging_integration}' callback configured in litellm_settings: {e}"+ ) from everbose_logger.exception("[Non-Blocking Error] Error initializing custom logger: %s", e)return None- return None+++def init_custom_logger_compatible_class_at_startup(+ callback: str,+ internal_usage_cache: DualCache | None,+ llm_router: object,+) -> CustomLogger | None:+ return _init_custom_logger_compatible_class(+ callback, internal_usage_cache=internal_usage_cache, llm_router=llm_router, raise_import_errors=True+ )def _maybe_construct_otel_v2(callback_name: str, _in_memory_loggers: list[CustomLogger]) -> "OpenTelemetryV2 | None":diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 267c87694b9..cf90d90ea33 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -271,7 +271,7 @@ from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointTfrom litellm.types.proxy.policy_engine.pipeline_types import PipelineExecutionResultfrom litellm.types.utils import LLMResponseTypes, LoggedLiteLLMParamsfrom litellm.utils import (- add_custom_logger_callback_to_specific_event,+ add_configured_callback_to_specific_event,)if TYPE_CHECKING:@@ -1440,18 +1440,21 @@ class ProxyLogging:# Track string callbacks and their initialized instances so we can# replace them in-place, preventing duplicates (string + instance) in# litellm.callbacks which caused double-counting of metrics.- string_callbacks_to_replace: Final[dict[int, CustomLogger]] = {}-- for idx, callback in enumerate(litellm.callbacks):- if isinstance(callback, str):- initialized_callback = litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class(- cast(_custom_logger_compatible_callbacks_literal, callback),+ built_string_callbacks: Final = (+ (+ idx,+ litellm.litellm_core_utils.litellm_logging.init_custom_logger_compatible_class_at_startup(+ callback,internal_usage_cache=self.internal_usage_cache.dual_cache,llm_router=llm_router,- )-- if initialized_callback is not None:- string_callbacks_to_replace[idx] = initialized_callback+ ),+ )+ for idx, callback in enumerate(litellm.callbacks)+ if isinstance(callback, str)+ )+ string_callbacks_to_replace: Final = MappingProxyType(+ {idx: built for idx, built in built_string_callbacks if built is not None}+ )# Replace string entries in litellm.callbacks with initialized instancesfor idx, initialized_callback in string_callbacks_to_replace.items():@@ -1477,9 +1480,9 @@ class ProxyLogging:success_callbacks: Final = tuple(cb for cb in litellm.success_callback if isinstance(cb, str))failure_callbacks: Final = tuple(cb for cb in litellm.failure_callback if isinstance(cb, str))for callback in success_callbacks:- add_custom_logger_callback_to_specific_event(callback, "success")+ add_configured_callback_to_specific_event(callback, "success")for callback in failure_callbacks:- add_custom_logger_callback_to_specific_event(callback, "failure")+ add_configured_callback_to_specific_event(callback, "failure")async def update_request_status(self, litellm_call_id: str, status: Literal["success", "fail"]):# only use this if slack alerting is being useddiff --git a/litellm/utils.py b/litellm/utils.pyindex b5511254e63..32248e6fd54 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -604,20 +604,38 @@ def add_custom_logger_callback_to_specific_event(callback: str, logging_event: L)if callback_class:- if logging_event == "success" and _custom_logger_class_exists_in_success_callbacks(callback_class) is False:- litellm.logging_callback_manager.add_litellm_success_callback(callback_class)- litellm.logging_callback_manager.add_litellm_async_success_callback(callback_class)- if callback in litellm.success_callback:- litellm.success_callback.remove(callback) # remove the string from the callback list- if callback in litellm._async_success_callback:- litellm._async_success_callback.remove(callback) # remove the string from the callback list- elif logging_event == "failure" and _custom_logger_class_exists_in_failure_callbacks(callback_class) is False:- litellm.logging_callback_manager.add_litellm_failure_callback(callback_class)- litellm.logging_callback_manager.add_litellm_async_failure_callback(callback_class)- if callback in litellm.failure_callback:- litellm.failure_callback.remove(callback) # remove the string from the callback list- if callback in litellm._async_failure_callback:- litellm._async_failure_callback.remove(callback) # remove the string from the callback list+ register_custom_logger_for_event(callback, callback_class, logging_event)+++def add_configured_callback_to_specific_event(callback: str, logging_event: Literal["success", "failure"]) -> None:+ from litellm.litellm_core_utils.litellm_logging import (+ init_custom_logger_compatible_class_at_startup,+ )++ callback_class: Final = init_custom_logger_compatible_class_at_startup(+ callback, internal_usage_cache=None, llm_router=None+ )+ if callback_class is not None:+ register_custom_logger_for_event(callback, callback_class, logging_event)+++def register_custom_logger_for_event(+ callback: str, callback_class: CustomLogger, logging_event: Literal["success", "failure"]+) -> None:+ if logging_event == "success" and _custom_logger_class_exists_in_success_callbacks(callback_class) is False:+ litellm.logging_callback_manager.add_litellm_success_callback(callback_class)+ litellm.logging_callback_manager.add_litellm_async_success_callback(callback_class)+ if callback in litellm.success_callback:+ litellm.success_callback.remove(callback) # remove the string from the callback list+ if callback in litellm._async_success_callback:+ litellm._async_success_callback.remove(callback) # remove the string from the callback list+ elif logging_event == "failure" and _custom_logger_class_exists_in_failure_callbacks(callback_class) is False:+ litellm.logging_callback_manager.add_litellm_failure_callback(callback_class)+ litellm.logging_callback_manager.add_litellm_async_failure_callback(callback_class)+ if callback in litellm.failure_callback:+ litellm.failure_callback.remove(callback) # remove the string from the callback list+ if callback in litellm._async_failure_callback:+ litellm._async_failure_callback.remove(callback) # remove the string from the callback list_add_custom_logger_callback_to_specific_event = add_custom_logger_callback_to_specific_eventdiff --git a/tests/unit/proxy/test_init_litellm_callbacks.py b/tests/unit/proxy/test_init_litellm_callbacks.pyindex 4ed33850602..6119a0a9efa 100644--- a/tests/unit/proxy/test_init_litellm_callbacks.py+++ b/tests/unit/proxy/test_init_litellm_callbacks.py@@ -50,7 +50,7 @@ class TestInitLitellmCallbacks:proxy_logging = self._make_proxy_logging()with patch(- "litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class",+ "litellm.litellm_core_utils.litellm_logging.build_custom_logger_compatible_class",return_value=fake_logger,):proxy_logging._init_litellm_callbacks(llm_router=None)@@ -107,7 +107,7 @@ class TestInitLitellmCallbacks:)def test_should_handle_unrecognized_string_callback(self, _mock_hooks):"""- When _init_custom_logger_compatible_class returns None for a string callback,+ When build_custom_logger_compatible_class returns None for a string callback,the string should remain in litellm.callbacks (not crash)."""litellm.callbacks = ["unknown_callback"] # type: ignore@@ -115,7 +115,7 @@ class TestInitLitellmCallbacks:proxy_logging = self._make_proxy_logging()with patch(- "litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class",+ "litellm.litellm_core_utils.litellm_logging.build_custom_logger_compatible_class",return_value=None,):proxy_logging._init_litellm_callbacks(llm_router=None)@@ -152,7 +152,7 @@ class TestInitLitellmCallbacks:return fake_logger_bwith patch(- "litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class",+ "litellm.litellm_core_utils.litellm_logging.build_custom_logger_compatible_class",side_effect=mock_init_class,):proxy_logging._init_litellm_callbacks(llm_router=None)diff --git a/tests/unit/proxy/utils/proxy_logging/test_lifecycle.py b/tests/unit/proxy/utils/proxy_logging/test_lifecycle.pyindex 40cb3f10d34..b9fee4591f7 100644--- a/tests/unit/proxy/utils/proxy_logging/test_lifecycle.py+++ b/tests/unit/proxy/utils/proxy_logging/test_lifecycle.py@@ -410,7 +410,7 @@ def test_init_litellm_callbacks_replaces_string_with_instance(proxy_logging, monmonkeypatch.setattr(litellm, "callbacks", ["some-string-logger"])monkeypatch.setattr(litellm.litellm_core_utils.litellm_logging,- "_init_custom_logger_compatible_class",+ "build_custom_logger_compatible_class",lambda *a, **kw: sentinel_instance,)@@ -434,7 +434,7 @@ def test_init_litellm_callbacks_string_resolution_failure_keeps_string(proxy_logmonkeypatch.setattr(litellm, "callbacks", ["unknown-logger"])monkeypatch.setattr(litellm.litellm_core_utils.litellm_logging,- "_init_custom_logger_compatible_class",+ "build_custom_logger_compatible_class",lambda *a, **kw: None,)monkeypatch.setattr(utils_mod, "PROXY_HOOKS", [])@@ -443,20 +443,40 @@ def test_init_litellm_callbacks_string_resolution_failure_keeps_string(proxy_logassert litellm.callbacks[0] == "unknown-logger"-def test_init_litellm_callbacks_propagates_resolver_error_raises(proxy_logging, monkeypatch):[email protected]("callback_list", ["callbacks", "success_callback", "failure_callback"])+def test_init_litellm_callbacks_fails_startup_on_a_configured_callback_with_an_unsupported_sdk(+ proxy_logging, monkeypatch, callback_list+):+ from litellm.integrations.langfuse import langfuse_prompt_management+ from litellm.integrations.langfuse.langfuse import UNSUPPORTED_LANGFUSE_VERSIONfrom litellm.proxy import utils as utils_mod- monkeypatch.setattr(litellm, "callbacks", ["raises-on-init"])+ monkeypatch.setattr(litellm.litellm_core_utils.litellm_logging, "_in_memory_loggers", [])monkeypatch.setattr(- litellm.litellm_core_utils.litellm_logging,- "_init_custom_logger_compatible_class",- MagicMock(side_effect=RuntimeError("bad init")),+ langfuse_prompt_management, "installed_langfuse_version", lambda: f"{UNSUPPORTED_LANGFUSE_VERSION}.0.0")+ monkeypatch.setattr(litellm, callback_list, ["langfuse"])monkeypatch.setattr(utils_mod, "PROXY_HOOKS", [])- with pytest.raises(RuntimeError):+ with pytest.raises(ImportError, match="'langfuse' callback configured in litellm_settings"):proxy_logging._init_litellm_callbacks(llm_router=None)+def test_init_litellm_callbacks_keeps_starting_when_a_configured_callback_fails_for_another_reason(+ proxy_logging, monkeypatch+):+ from litellm.integrations.langfuse import langfuse_prompt_management+ from litellm.integrations.langfuse.langfuse import MINIMUM_LANGFUSE_VERSION, PROMPT_CACHE_TTL_ENV+ from litellm.proxy import utils as utils_mod++ monkeypatch.setattr(litellm.litellm_core_utils.litellm_logging, "_in_memory_loggers", [])+ monkeypatch.setattr(langfuse_prompt_management, "installed_langfuse_version", lambda: MINIMUM_LANGFUSE_VERSION)+ monkeypatch.setenv(PROMPT_CACHE_TTL_ENV, "not-a-number")+ monkeypatch.setattr(litellm, "success_callback", ["langfuse"])+ monkeypatch.setattr(utils_mod, "PROXY_HOOKS", [])+ proxy_logging._init_litellm_callbacks(llm_router=None)+ assert "langfuse" in litellm.success_callback++# ---------------------------------------------------------------------------# update_request_status# ---------------------------------------------------------------------------