Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /BerriAI_litellm /litellm /integrations /datadog /datadog.py
| """ | |
| DataDog Integration - sends logs to /api/v2/log | |
| DD Reference API: https://docs.datadoghq.com/api/latest/logs | |
| `async_log_success_event` - used by litellm proxy to send logs to datadog | |
| `log_success_event` - sync version of logging to DataDog, only used on litellm Python SDK, if user opts in to using sync functions | |
| async_log_success_event: will store batch of DD_MAX_BATCH_SIZE in memory and flush to Datadog once it reaches DD_MAX_BATCH_SIZE or every 5 seconds | |
| async_service_failure_hook: Logs failures from Redis, Postgres (Adjacent systems), as 'WARNING' on DataDog | |
| For batching specific details see CustomBatchLogger class | |
| """ | |
| import asyncio | |
| import datetime | |
| import os | |
| import time | |
| import traceback | |
| from collections.abc import Sequence | |
| from datetime import datetime as datetimeObj | |
| from typing import TYPE_CHECKING, Any, Final | |
| import httpx | |
| from httpx import Response | |
| from typing_extensions import ReadOnly, TypedDict | |
| import litellm | |
| from litellm._logging import verbose_logger | |
| from litellm._uuid import uuid | |
| from litellm.integrations.batch_utils import BatchSendCancelled, requeue_after_http_error, send_batch_with_413_split | |
| from litellm.integrations.custom_batch_logger import CustomBatchLogger | |
| from litellm.integrations.datadog.datadog_handler import ( | |
| get_datadog_base_url_from_env, | |
| get_datadog_hostname, | |
| get_datadog_service, | |
| get_datadog_source, | |
| get_datadog_tags, | |
| ) | |
| from litellm.integrations.datadog.datadog_mock_client import ( | |
| create_mock_datadog_client, | |
| should_use_datadog_mock, | |
| ) | |
| from litellm.litellm_core_utils.dd_tracing import tracer | |
| from litellm.llms.custom_httpx.http_handler import ( | |
| _get_httpx_client, | |
| get_async_httpx_client, | |
| httpxSpecialProvider, | |
| ) | |
| from litellm.types.integrations.base_health_check import IntegrationHealthCheckStatus | |
| from litellm.types.integrations.datadog import ( | |
| DD_ERRORS, | |
| DD_MAX_BATCH_SIZE, | |
| DD_MAX_PAYLOAD_SIZE_BYTES, | |
| DatadogInitParams, | |
| DatadogPayload, | |
| DatadogProxyFailureHookJsonMessage, | |
| DataDogStatus, | |
| ) | |
| from litellm.types.services import ServiceLoggerPayload, ServiceTypes | |
| from litellm.types.utils import StandardLoggingPayload | |
| from ..additional_logging_utils import AdditionalLoggingUtils | |
| if TYPE_CHECKING: | |
| from fastapi import HTTPException | |
| from litellm.proxy._types import UserAPIKeyAuth | |
| class _DatadogLoggingKwargs(TypedDict, total=False): | |
| """The subset of logging ``kwargs`` that the Datadog payload builder reads.""" | |
| standard_logging_object: ReadOnly[StandardLoggingPayload | None] | |
| # max number of logs DD API can accept | |
| # specify what ServiceTypes are logged as success events to DD. (We don't want to spam DD traces with large number of service types) | |
| DD_LOGGED_SUCCESS_SERVICE_TYPES: Final = [ | |
| ServiceTypes.RESET_BUDGET_JOB, | |
| ] | |
| def _resolve_dd_batch_size() -> int: | |
| raw: Final = os.getenv("DD_BATCH_SIZE") | |
| if raw is None: | |
| return DD_MAX_BATCH_SIZE | |
| try: | |
| value: Final = int(raw) | |
| except ValueError: | |
| verbose_logger.warning( | |
| "Datadog: ignoring invalid DD_BATCH_SIZE=%r, using %s", | |
| raw, | |
| DD_MAX_BATCH_SIZE, | |
| ) | |
| return DD_MAX_BATCH_SIZE | |
| return max(1, min(value, DD_MAX_BATCH_SIZE)) | |
| def _span_attribute(span: object, name: str) -> object: | |
| """Read an optional attribute off whatever span object the active tracer hands back.""" | |
| return getattr(span, name, None) | |
| class DataDogLogger( | |
| CustomBatchLogger, | |
| AdditionalLoggingUtils, | |
| ): | |
| # Class variables or attributes | |
| def __init__( | |
| self, | |
| dd_api_key: str | None = None, | |
| dd_site: str | None = None, | |
| dd_agent_host: str | None = None, | |
| dd_agent_port: str | None = None, | |
| allow_env_credentials: bool = True, | |
| **kwargs, | |
| ): | |
| """ | |
| Initializes the datadog logger, checks if the correct env variables are set | |
| Args: | |
| dd_api_key: Datadog API key. Falls back to DD_API_KEY env var when allow_env_credentials is True. | |
| dd_site: Datadog site (e.g. "us5.datadoghq.com"). Falls back to DD_SITE env var. | |
| dd_agent_host: Hostname or IP of DataDog agent. Falls back to LITELLM_DD_AGENT_HOST env var. | |
| dd_agent_port: Port of DataDog agent (default: 10518). Falls back to LITELLM_DD_AGENT_PORT env var. | |
| allow_env_credentials: When False, the API key is never read from DD_API_KEY env var. Set to | |
| False for team/key-scoped loggers whose destination (dd_agent_host/dd_site) is caller-supplied, | |
| so the proxy's global DD_API_KEY is never sent to an untrusted host. | |
| Required environment variables (Direct API) when kwargs not provided: | |
| `DD_API_KEY` - your datadog api key | |
| `DD_SITE` - your datadog site, example = `"us5.datadoghq.com"` | |
| Optional environment variables (DataDog Agent): | |
| `LITELLM_DD_AGENT_HOST` - hostname or IP of DataDog agent, example = `"localhost"` | |
| `LITELLM_DD_AGENT_PORT` - port of DataDog agent (default: 10518 for logs) | |
| Note: We use LITELLM_DD_AGENT_HOST instead of DD_AGENT_HOST to avoid conflicts | |
| with ddtrace which automatically sets DD_AGENT_HOST for APM tracing. | |
| """ | |
| try: | |
| verbose_logger.debug("Datadog: in init datadog logger") | |
| self.is_mock_mode = should_use_datadog_mock() | |
| if self.is_mock_mode: | |
| create_mock_datadog_client() | |
| verbose_logger.debug("[DATADOG MOCK] Datadog logger initialized in mock mode") | |
| ######################################################### | |
| # Handle datadog_params set as litellm.datadog_params | |
| ######################################################### | |
| dict_datadog_params: Final = self._get_datadog_params() | |
| kwargs.update(dict_datadog_params) | |
| self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) | |
| # Configure DataDog endpoint (Agent or Direct API) | |
| # Prefer explicit kwargs, then fall back to env vars | |
| resolved_agent_host: Final = dd_agent_host or os.getenv("LITELLM_DD_AGENT_HOST") | |
| if resolved_agent_host: | |
| self._configure_dd_agent( | |
| dd_agent_host=resolved_agent_host, | |
| dd_agent_port=dd_agent_port, | |
| dd_api_key=dd_api_key, | |
| allow_env_credentials=allow_env_credentials, | |
| ) | |
| else: | |
| self._configure_dd_direct_api( | |
| dd_api_key=dd_api_key, | |
| dd_site=dd_site, | |
| allow_env_credentials=allow_env_credentials, | |
| ) | |
| # Optional override for testing | |
| dd_base_url: Final = get_datadog_base_url_from_env() | |
| if dd_base_url: | |
| self.intake_url = f"{dd_base_url}/api/v2/logs" | |
| self.sync_client = _get_httpx_client() | |
| asyncio.create_task(self.periodic_flush()) | |
| self.flush_lock = asyncio.Lock() | |
| super().__init__( | |
| **kwargs, | |
| flush_lock=self.flush_lock, | |
| batch_size=_resolve_dd_batch_size(), | |
| ) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog: Got exception on init Datadog client %s", e) | |
| raise e | |
| def _get_datadog_params(self) -> dict: | |
| """ | |
| Get the datadog_params from litellm.datadog_params | |
| These are params specific to initializing the DataDogLogger e.g. turn_off_message_logging | |
| """ | |
| dict_datadog_params: dict = {} | |
| if litellm.datadog_params is not None: | |
| if isinstance(litellm.datadog_params, DatadogInitParams): | |
| dict_datadog_params = litellm.datadog_params.model_dump() | |
| elif isinstance(litellm.datadog_params, dict): | |
| # only allow params that are of DatadogInitParams | |
| dict_datadog_params = DatadogInitParams(**litellm.datadog_params).model_dump() | |
| return dict_datadog_params | |
| def _configure_dd_agent( | |
| self, | |
| dd_agent_host: str, | |
| dd_agent_port: str | None = None, | |
| dd_api_key: str | None = None, | |
| allow_env_credentials: bool = True, | |
| ) -> None: | |
| """ | |
| Configure DataDog Agent for log forwarding | |
| Args: | |
| dd_agent_host: Hostname or IP of DataDog agent | |
| dd_agent_port: Port of DataDog agent. Falls back to LITELLM_DD_AGENT_PORT env var (default: 10518). | |
| dd_api_key: Datadog API key. Falls back to DD_API_KEY env var when allow_env_credentials is True. Optional when using agent. | |
| allow_env_credentials: When False, never read the API key from DD_API_KEY env var. | |
| """ | |
| resolved_port: Final = dd_agent_port or os.getenv("LITELLM_DD_AGENT_PORT", "10518") # default port for logs | |
| self.intake_url = f"http://{dd_agent_host}:{resolved_port}/api/v2/logs" | |
| self.DD_API_KEY = dd_api_key or ( | |
| os.getenv("DD_API_KEY") if allow_env_credentials else None | |
| ) # Optional when using agent | |
| verbose_logger.debug("Datadog: Using DD Agent at %s", self.intake_url) | |
| def _configure_dd_direct_api( | |
| self, | |
| dd_api_key: str | None = None, | |
| dd_site: str | None = None, | |
| allow_env_credentials: bool = True, | |
| ) -> None: | |
| """ | |
| Configure direct DataDog API connection | |
| Args: | |
| dd_api_key: Datadog API key. Falls back to DD_API_KEY env var when allow_env_credentials is True. | |
| dd_site: Datadog site. Falls back to DD_SITE env var. | |
| allow_env_credentials: When False, never read the API key from DD_API_KEY env var. | |
| Raises: | |
| Exception: If required credentials are not provided via args or env vars | |
| """ | |
| resolved_api_key: Final = dd_api_key or (os.getenv("DD_API_KEY") if allow_env_credentials else None) | |
| resolved_site: Final = dd_site or os.getenv("DD_SITE") | |
| if resolved_api_key is None: | |
| raise Exception("DD_API_KEY is not set, set 'DD_API_KEY=<>") | |
| if resolved_site is None: | |
| raise Exception("DD_SITE is not set in .env, set 'DD_SITE=<>") | |
| self.DD_API_KEY = resolved_api_key | |
| self.intake_url = f"https://http-intake.logs.{resolved_site}/api/v2/logs" | |
| async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| """ | |
| Async Log success events to Datadog | |
| - Creates a Datadog payload | |
| - Adds the Payload to the in memory logs queue | |
| - Payload is flushed every 10 seconds or when batch size is greater than 100 | |
| Raises: | |
| Raises a NON Blocking verbose_logger.exception if an error occurs | |
| """ | |
| try: | |
| verbose_logger.debug("Datadog: Logging - Enters logging function for model %s", kwargs) | |
| await self._log_async_event(kwargs, response_obj, start_time, end_time) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog Layer Error - %s\n%s", e, traceback.format_exc()) | |
| async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): | |
| try: | |
| verbose_logger.debug("Datadog: Logging - Enters logging function for model %s", kwargs) | |
| await self._log_async_event(kwargs, response_obj, start_time, end_time) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog Layer Error - %s\n%s", e, traceback.format_exc()) | |
| async def async_post_call_failure_hook( | |
| self, | |
| request_data: dict, | |
| original_exception: Exception, | |
| user_api_key_dict: "UserAPIKeyAuth", | |
| traceback_str: str | None = None, | |
| ) -> "HTTPException | None": | |
| """ | |
| Log proxy-level failures (e.g. 401 auth, DB connection errors) to Datadog. | |
| Ensures failures that occur before or outside the LLM completion flow | |
| (e.g. ConnectError during auth when DB is down) are visible in Datadog | |
| alongside Prometheus. | |
| """ | |
| try: | |
| from litellm.litellm_core_utils.litellm_logging import ( | |
| StandardLoggingPayloadSetup, | |
| ) | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| error_information: Final = StandardLoggingPayloadSetup.get_error_information( | |
| original_exception=original_exception, | |
| traceback_str=traceback_str, | |
| ) | |
| _code: Final = error_information.get("error_code") or "" | |
| status_code: int | None = None | |
| if _code and str(_code).strip().isdigit(): | |
| status_code = int(_code) | |
| # Use project-standard sanitized user context when running in proxy | |
| user_context: dict[str, object] = {} | |
| try: | |
| from litellm.proxy.litellm_pre_call_utils import ( | |
| LiteLLMProxyRequestSetup, | |
| ) | |
| _meta: Final = LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key( | |
| user_api_key_dict=user_api_key_dict | |
| ) | |
| user_context = dict(_meta) if isinstance(_meta, dict) else _meta | |
| except Exception: | |
| # Fallback if proxy not available (e.g. SDK-only): minimal safe fields | |
| if hasattr(user_api_key_dict, "request_route"): | |
| user_context["request_route"] = getattr(user_api_key_dict, "request_route", None) | |
| if hasattr(user_api_key_dict, "team_id"): | |
| user_context["team_id"] = getattr(user_api_key_dict, "team_id", None) | |
| if hasattr(user_api_key_dict, "user_id"): | |
| user_context["user_id"] = getattr(user_api_key_dict, "user_id", None) | |
| if hasattr(user_api_key_dict, "end_user_id"): | |
| user_context["end_user_id"] = getattr(user_api_key_dict, "end_user_id", None) | |
| message_payload: Final[DatadogProxyFailureHookJsonMessage] = { | |
| "exception": error_information.get("error_message") or str(original_exception), | |
| "error_class": error_information.get("error_class") or original_exception.__class__.__name__, | |
| "status_code": status_code, | |
| "traceback": error_information.get("traceback") or "", | |
| "user_api_key_dict": user_context, | |
| } | |
| dd_payload: Final = DatadogPayload( | |
| ddsource=get_datadog_source(), | |
| ddtags=",".join(get_datadog_tags()), | |
| hostname=get_datadog_hostname(), | |
| message=safe_dumps(message_payload), | |
| service=get_datadog_service(), | |
| status=DataDogStatus.ERROR, | |
| ) | |
| self._add_trace_context_to_payload(dd_payload=dd_payload) | |
| self.log_queue.append(dd_payload) | |
| if len(self.log_queue) >= self.batch_size: | |
| await self.flush_queue() | |
| except Exception as e: | |
| verbose_logger.exception("Datadog: async_post_call_failure_hook - %s\n%s", e, traceback.format_exc()) | |
| return None | |
| async def async_send_batch(self): | |
| """ | |
| Sends the in memory logs queue to datadog api | |
| Logs sent to /api/v2/logs | |
| DD Ref: https://docs.datadoghq.com/api/latest/logs/ | |
| Raises: | |
| Raises a NON Blocking verbose_logger.exception if an error occurs | |
| """ | |
| if not self.log_queue: | |
| verbose_logger.exception("Datadog: log_queue does not exist") | |
| return | |
| batch_to_send: Final = self.log_queue[:] | |
| self.log_queue = [] | |
| try: | |
| verbose_logger.debug( | |
| "Datadog - about to flush %s events on %s", | |
| len(batch_to_send), | |
| self.intake_url, | |
| ) | |
| if self.is_mock_mode: | |
| verbose_logger.debug("[DATADOG MOCK] Mock mode enabled - API calls will be intercepted") | |
| undelivered: Final = await self._send_with_413_split(batch_to_send) | |
| if undelivered: | |
| self.log_queue = undelivered + self.log_queue | |
| if self.is_mock_mode: | |
| verbose_logger.debug("[DATADOG MOCK] Batch of %s events successfully mocked", len(batch_to_send)) | |
| except BatchSendCancelled as cancelled: | |
| self.log_queue = list(cancelled.undelivered) + self.log_queue # mutable-ok: logger queue remains appendable | |
| raise asyncio.CancelledError() from cancelled | |
| except Exception as e: | |
| self.log_queue = batch_to_send + self.log_queue | |
| verbose_logger.exception("Datadog Error sending batch API - %s\n%s", e, traceback.format_exc()) | |
| async def _send_with_413_split(self, batch: list) -> list: | |
| """ | |
| Send a batch, halving any sub-batch that exceeds Datadog's intake limits before | |
| sending, and halving again on a 413 (payload too large) response, since Datadog | |
| enforces a 5MB uncompressed limit per request. The proactive split avoids paying | |
| a serialize + gzip + round trip for a payload the intake is guaranteed to reject. | |
| A 413 surfaces as a raised MaskedHTTPStatusError (httpx raise_for_status), not a | |
| returned response, so both paths are handled. A lone event that still 413s is | |
| dropped to avoid wedging the queue on an undeliverable payload. Returns the events | |
| that could not be delivered because of a non-413 (transient) error, so the caller | |
| re-queues only those and never the events already accepted by Datadog. | |
| """ | |
| undelivered: Final = await send_batch_with_413_split( | |
| batch=batch, | |
| send_batch=self.async_send_compressed_data, | |
| exceeds_limits=self._exceeds_intake_limits, | |
| success_status_codes=frozenset({202}), | |
| integration_name="Datadog", | |
| drop_error_message=DD_ERRORS.DATADOG_413_ERROR.value, | |
| non_success_handler=requeue_after_http_error, | |
| ) | |
| return list(undelivered) # mutable-ok: caller prepends records to the logger queue | |
| def _exceeds_intake_limits(chunk: Sequence[DatadogPayload]) -> bool: | |
| """ | |
| True when a chunk would breach Datadog's log intake limits: more than | |
| DD_MAX_BATCH_SIZE events per payload, or a serialized size above | |
| DD_MAX_PAYLOAD_SIZE_BYTES (held under Datadog's 5MB uncompressed cap so | |
| the batch is split before the intake rejects it with a 413). | |
| """ | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| if len(chunk) > DD_MAX_BATCH_SIZE: | |
| return True | |
| payload_size_bytes: Final = len(safe_dumps(chunk).encode("utf-8")) | |
| return payload_size_bytes > DD_MAX_PAYLOAD_SIZE_BYTES | |
| async def flush_queue(self): | |
| if self.flush_lock is None: | |
| return | |
| async with self.flush_lock: | |
| if self.log_queue: | |
| verbose_logger.debug("Datadog: Flushing batch of %s events", len(self.log_queue)) | |
| await self.async_send_batch() | |
| if not self.log_queue: | |
| self.last_flush_time = time.time() | |
| def log_success_event(self, kwargs, response_obj, start_time, end_time): | |
| """ | |
| Sync Log success events to Datadog | |
| - Creates a Datadog payload | |
| - instantly logs it on DD API | |
| """ | |
| try: | |
| if litellm.datadog_use_v1 is True: | |
| dd_payload = self._create_v0_logging_payload( | |
| kwargs=kwargs, | |
| response_obj=response_obj, | |
| start_time=start_time, | |
| end_time=end_time, | |
| ) | |
| else: | |
| dd_payload = self.create_datadog_logging_payload( | |
| kwargs=kwargs, | |
| response_obj=response_obj, | |
| start_time=start_time, | |
| end_time=end_time, | |
| ) | |
| # Build headers | |
| headers: Final = {} | |
| # Add API key if available (required for direct API, optional for agent) | |
| if self.DD_API_KEY: | |
| headers["DD-API-KEY"] = self.DD_API_KEY | |
| response: Final = self.sync_client.post( | |
| url=self.intake_url, | |
| json=dd_payload, | |
| headers=headers, | |
| ) | |
| response.raise_for_status() | |
| if response.status_code != 202: | |
| raise Exception(f"Response from datadog API status_code: {response.status_code}, text: {response.text}") | |
| verbose_logger.debug( | |
| "Datadog: Response from datadog API status_code: %s, text: %s", | |
| response.status_code, | |
| response.text, | |
| ) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog Layer Error - %s\n%s", e, traceback.format_exc()) | |
| async def _log_async_event(self, kwargs, response_obj, start_time, end_time): | |
| dd_payload: Final = self.create_datadog_logging_payload( | |
| kwargs=kwargs, | |
| response_obj=response_obj, | |
| start_time=start_time, | |
| end_time=end_time, | |
| ) | |
| self.log_queue.append(dd_payload) | |
| verbose_logger.debug("Datadog, event added to queue. Will flush in %s seconds...", self.flush_interval) | |
| if len(self.log_queue) >= self.batch_size: | |
| await self.flush_queue() | |
| def _create_datadog_logging_payload_helper( | |
| self, | |
| standard_logging_object: StandardLoggingPayload, | |
| status: DataDogStatus, | |
| ) -> DatadogPayload: | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| json_payload: Final = safe_dumps(standard_logging_object) | |
| verbose_logger.debug("Datadog: Logger - Logging payload = %s", json_payload) | |
| dd_payload: Final = DatadogPayload( | |
| ddsource=get_datadog_source(), | |
| ddtags=",".join(get_datadog_tags(standard_logging_object=standard_logging_object)), | |
| hostname=get_datadog_hostname(), | |
| message=json_payload, | |
| service=get_datadog_service(), | |
| status=status, | |
| ) | |
| self._add_trace_context_to_payload(dd_payload=dd_payload) | |
| return dd_payload | |
| def create_datadog_logging_payload( | |
| self, | |
| kwargs: _DatadogLoggingKwargs, | |
| response_obj: object, | |
| start_time: datetime.datetime, | |
| end_time: datetime.datetime, | |
| ) -> DatadogPayload: | |
| """ | |
| Helper function to create a datadog payload for logging | |
| Args: | |
| kwargs: request kwargs, read for its standard logging object | |
| response_obj: llm api response | |
| start_time (datetime.datetime): start time of request | |
| end_time (datetime.datetime): end time of request | |
| Returns: | |
| DatadogPayload: defined in types.py | |
| """ | |
| standard_logging_object: Final[StandardLoggingPayload | None] = kwargs.get("standard_logging_object", None) | |
| if standard_logging_object is None: | |
| raise ValueError("standard_logging_object not found in kwargs") | |
| status = DataDogStatus.INFO | |
| if standard_logging_object.get("status") == "failure": | |
| status = DataDogStatus.ERROR | |
| # Build the initial payload | |
| self.truncate_standard_logging_payload_content(standard_logging_object) | |
| dd_payload: Final = self._create_datadog_logging_payload_helper( | |
| standard_logging_object=standard_logging_object, | |
| status=status, | |
| ) | |
| return dd_payload | |
| async def async_send_compressed_data(self, data: Sequence[DatadogPayload]) -> Response: | |
| """ | |
| Async helper to send compressed data to datadog self.intake_url | |
| Datadog recommends using gzip to compress data | |
| https://docs.datadoghq.com/api/latest/logs/ | |
| "Datadog recommends sending your logs compressed. Add the Content-Encoding: gzip header to the request when sending" | |
| """ | |
| import gzip | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| compressed_data: Final = gzip.compress(safe_dumps(data).encode("utf-8")) | |
| # Build headers | |
| headers: Final = { | |
| "Content-Encoding": "gzip", | |
| "Content-Type": "application/json", | |
| } | |
| # Add API key if available (required for direct API, optional for agent) | |
| if self.DD_API_KEY: | |
| headers["DD-API-KEY"] = self.DD_API_KEY | |
| response: Final = await self.async_client.post( | |
| url=self.intake_url, | |
| data=compressed_data, | |
| headers=headers, | |
| ) | |
| return response | |
| async def async_service_failure_hook( | |
| self, | |
| payload: ServiceLoggerPayload, | |
| error: str | None = "", | |
| parent_otel_span: object = None, | |
| start_time: datetimeObj | float | None = None, | |
| end_time: float | datetimeObj | None = None, | |
| event_metadata: dict | None = None, | |
| ): | |
| """ | |
| Logs failures from Redis, Postgres (Adjacent systems), as 'WARNING' on DataDog | |
| - example - Redis is failing / erroring, will be logged on DataDog | |
| """ | |
| try: | |
| _payload_dict: Final = payload.model_dump() | |
| _payload_dict.update(event_metadata or {}) | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| _dd_message_str: Final = safe_dumps(_payload_dict) | |
| _dd_payload: Final = DatadogPayload( | |
| ddsource=get_datadog_source(), | |
| ddtags=",".join(get_datadog_tags()), | |
| hostname=get_datadog_hostname(), | |
| message=_dd_message_str, | |
| service=get_datadog_service(), | |
| status=DataDogStatus.WARN, | |
| ) | |
| self.log_queue.append(_dd_payload) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog: Logger - Exception in async_service_failure_hook: %s", e) | |
| async def async_service_success_hook( | |
| self, | |
| payload: ServiceLoggerPayload, | |
| error: str | None = "", | |
| parent_otel_span: object = None, | |
| start_time: datetimeObj | float | None = None, | |
| end_time: float | datetimeObj | None = None, | |
| event_metadata: dict | None = None, | |
| ): | |
| """ | |
| Logs success from Redis, Postgres (Adjacent systems), as 'INFO' on DataDog | |
| No user has asked for this so far, this might be spammy on datatdog. If need arises we can implement this | |
| """ | |
| try: | |
| # intentionally done. Don't want to log all service types to DD | |
| if payload.service not in DD_LOGGED_SUCCESS_SERVICE_TYPES: | |
| return | |
| _payload_dict: Final = payload.model_dump() | |
| _payload_dict.update(event_metadata or {}) | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| _dd_message_str: Final = safe_dumps(_payload_dict) | |
| _dd_payload: Final = DatadogPayload( | |
| ddsource=get_datadog_source(), | |
| ddtags=",".join(get_datadog_tags()), | |
| hostname=get_datadog_hostname(), | |
| message=_dd_message_str, | |
| service=get_datadog_service(), | |
| status=DataDogStatus.INFO, | |
| ) | |
| self.log_queue.append(_dd_payload) | |
| except Exception as e: | |
| verbose_logger.exception("Datadog: Logger - Exception in async_service_failure_hook: %s", e) | |
| def _create_v0_logging_payload( | |
| self, | |
| kwargs: dict, | |
| response_obj: Any, | |
| start_time: datetime.datetime, | |
| end_time: datetime.datetime, | |
| ) -> DatadogPayload: | |
| """ | |
| Note: This is our V1 Version of DataDog Logging Payload | |
| (Not Recommended) If you want this to get logged set `litellm.datadog_use_v1 = True` | |
| """ | |
| litellm_params: Final = kwargs.get("litellm_params", {}) | |
| metadata: Final = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None | |
| messages: Final = kwargs.get("messages") | |
| optional_params: Final = kwargs.get("optional_params", {}) | |
| call_type: Final = kwargs.get("call_type", "litellm.completion") | |
| cache_hit: Final = kwargs.get("cache_hit", False) | |
| usage = response_obj["usage"] | |
| id: Final = response_obj.get("id", str(uuid.uuid4())) | |
| usage = dict(usage) | |
| try: | |
| response_time = (end_time - start_time).total_seconds() * 1000 | |
| except Exception: | |
| response_time = None | |
| try: | |
| response_obj = dict(response_obj) | |
| except Exception: | |
| response_obj = response_obj | |
| # Clean Metadata before logging - never log raw metadata | |
| # the raw metadata can contain circular references which leads to infinite recursion | |
| # we clean out all extra litellm metadata params before logging | |
| clean_metadata: Final = {} | |
| if isinstance(metadata, dict): | |
| for key, value in metadata.items(): | |
| # clean litellm metadata before logging | |
| if key in [ | |
| "endpoint", | |
| "caching_groups", | |
| "previous_models", | |
| ]: | |
| continue | |
| else: | |
| clean_metadata[key] = value | |
| # Build the initial payload | |
| payload: Final = { | |
| "id": id, | |
| "call_type": call_type, | |
| "cache_hit": cache_hit, | |
| "start_time": start_time, | |
| "end_time": end_time, | |
| "response_time": response_time, | |
| "model": kwargs.get("model", ""), | |
| "user": kwargs.get("user", ""), | |
| "model_parameters": optional_params, | |
| "spend": kwargs.get("response_cost", 0), | |
| "messages": messages, | |
| "response": response_obj, | |
| "usage": usage, | |
| "metadata": clean_metadata, | |
| } | |
| from litellm.litellm_core_utils.safe_json_dumps import safe_dumps | |
| json_payload: Final = safe_dumps(payload) | |
| verbose_logger.debug("Datadog: Logger - Logging payload = %s", json_payload) | |
| dd_payload: Final = DatadogPayload( | |
| ddsource=get_datadog_source(), | |
| ddtags=",".join(get_datadog_tags()), | |
| hostname=get_datadog_hostname(), | |
| message=json_payload, | |
| service=get_datadog_service(), | |
| status=DataDogStatus.INFO, | |
| ) | |
| return dd_payload | |
| def _add_trace_context_to_payload( | |
| self, | |
| dd_payload: DatadogPayload, | |
| ) -> None: | |
| """Attach Datadog APM trace context if one is active.""" | |
| try: | |
| trace_context: Final = self._get_active_trace_context() | |
| if trace_context is None: | |
| return | |
| dd_payload["dd.trace_id"] = trace_context["trace_id"] | |
| span_id: Final = trace_context.get("span_id") | |
| if span_id is not None: | |
| dd_payload["dd.span_id"] = span_id | |
| except Exception: | |
| verbose_logger.exception("Datadog: Failed to attach trace context to payload") | |
| def _get_active_trace_context(self) -> dict[str, str] | None: | |
| try: | |
| current_span = None | |
| current_span_fn: Final = getattr(tracer, "current_span", None) | |
| if callable(current_span_fn): | |
| current_span = current_span_fn() | |
| if current_span is None: | |
| current_root_span_fn: Final = getattr(tracer, "current_root_span", None) | |
| if callable(current_root_span_fn): | |
| current_span = current_root_span_fn() | |
| if current_span is None: | |
| return None | |
| trace_id: Final = _span_attribute(current_span, "trace_id") | |
| if trace_id is None: | |
| return None | |
| span_id: Final = _span_attribute(current_span, "span_id") | |
| trace_context: Final[dict[str, str]] = {"trace_id": str(trace_id)} | |
| if span_id is not None: | |
| trace_context["span_id"] = str(span_id) | |
| return trace_context | |
| except Exception: | |
| verbose_logger.exception("Datadog: Failed to retrieve active trace context from tracer") | |
| return None | |
| async def async_health_check(self) -> IntegrationHealthCheckStatus: | |
| """ | |
| Check if the service is healthy | |
| """ | |
| from litellm.litellm_core_utils.litellm_logging import ( | |
| create_dummy_standard_logging_payload, | |
| ) | |
| standard_logging_object: Final = create_dummy_standard_logging_payload() | |
| dd_payload: Final = self._create_datadog_logging_payload_helper( | |
| standard_logging_object=standard_logging_object, | |
| status=DataDogStatus.INFO, | |
| ) | |
| log_queue: Final = [dd_payload] | |
| response: Final = await self.async_send_compressed_data(log_queue) | |
| try: | |
| response.raise_for_status() | |
| return IntegrationHealthCheckStatus( | |
| status="healthy", | |
| error_message=None, | |
| ) | |
| except httpx.HTTPStatusError as e: | |
| return IntegrationHealthCheckStatus( | |
| status="unhealthy", | |
| error_message=e.response.text, | |
| ) | |
| except Exception as e: | |
| return IntegrationHealthCheckStatus( | |
| status="unhealthy", | |
| error_message=str(e), | |
| ) | |
| async def get_request_response_payload( | |
| self, | |
| request_id: str, | |
| start_time_utc: datetimeObj | None, | |
| end_time_utc: datetimeObj | None, | |
| ) -> dict | None: | |
| pass | |
Xet Storage Details
- Size:
- 33.8 kB
- Xet hash:
- bf975aa2bb4310826ffed0706245d2173565ff79044d52c6755390804224e840
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.