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:Parse embedded JSON in the message field of logs (#20366)
Harshit Jaindfbc0e21568a
diff --git a/litellm/_logging.py b/litellm/_logging.pyindex e222627e76c..fd833f7056a 100644--- a/litellm/_logging.py+++ b/litellm/_logging.py@@ -1,9 +1,13 @@-import json+import astimport loggingimport osimport sysfrom datetime import datetimefrom logging import Formatter+from typing import Any, Dict, Optional++from litellm.litellm_core_utils.safe_json_dumps import safe_dumps+from litellm.litellm_core_utils.safe_json_loads import safe_json_loadsset_verbose = False@@ -19,6 +23,67 @@ handler = logging.StreamHandler()handler.setLevel(numeric_level)+def _try_parse_json_message(message: str) -> Optional[Dict[str, Any]]:+ """+ Try to parse a log message as JSON. Returns parsed dict if valid, else None.+ Handles messages that are entirely valid JSON (e.g. json.dumps output).+ Uses shared safe_json_loads for consistent error handling.+ """+ if not message or not isinstance(message, str):+ return None+ msg_stripped = message.strip()+ if not (msg_stripped.startswith("{") or msg_stripped.startswith("[")):+ return None+ parsed = safe_json_loads(message, default=None)+ if parsed is None or not isinstance(parsed, dict):+ return None+ return parsed+++def _try_parse_embedded_python_dict(message: str) -> Optional[Dict[str, Any]]:+ """+ Try to find and parse a Python dict repr (e.g. str(d) or repr(d)) embedded in+ the message. Handles patterns like:+ "get_available_deployment for model: X, Selected deployment: {'model_name': '...', ...} for model: X"+ Uses ast.literal_eval for safe parsing. Returns the parsed dict or None.+ """+ if not message or not isinstance(message, str) or "{" not in message:+ return None+ i = 0+ while i < len(message):+ start = message.find("{", i)+ if start == -1:+ break+ depth = 0+ for j in range(start, len(message)):+ c = message[j]+ if c == "{":+ depth += 1+ elif c == "}":+ depth -= 1+ if depth == 0:+ substr = message[start : j + 1]+ try:+ result = ast.literal_eval(substr)+ if isinstance(result, dict) and len(result) > 0:+ return result+ except (ValueError, SyntaxError, TypeError):+ pass+ break+ i = start + 1+ return None+++# Standard LogRecord attribute names - used to identify 'extra' fields.+# Derived at runtime so we automatically include version-specific attrs (e.g. taskName).+def _get_standard_record_attrs() -> frozenset:+ """Standard LogRecord attribute names - excludes extra keys from logger.debug(..., extra={...})."""+ return frozenset(logging.LogRecord("", 0, "", 0, "", (), None).__dict__.keys())+++_STANDARD_RECORD_ATTRS = _get_standard_record_attrs()++class JsonFormatter(Formatter):def __init__(self):super(JsonFormatter, self).__init__()@@ -29,16 +94,31 @@ class JsonFormatter(Formatter):return dt.isoformat()def format(self, record):- json_record = {- "message": record.getMessage(),+ message_str = record.getMessage()+ json_record: Dict[str, Any] = {+ "message": message_str,"level": record.levelname,"timestamp": self.formatTime(record),}+ # Parse embedded JSON or Python dict repr in message so sub-fields become first-class properties+ parsed = _try_parse_json_message(message_str)+ if parsed is None:+ parsed = _try_parse_embedded_python_dict(message_str)+ if parsed is not None:+ for key, value in parsed.items():+ if key not in json_record:+ json_record[key] = value++ # Include extra attributes passed via logger.debug("msg", extra={...})+ for key, value in record.__dict__.items():+ if key not in _STANDARD_RECORD_ATTRS and key not in json_record:+ json_record[key] = value+if record.exc_info:json_record["stacktrace"] = self.formatException(record.exc_info)- return json.dumps(json_record)+ return safe_dumps(json_record)# Function to set up exception handlers for JSON logging@@ -169,15 +249,15 @@ def _initialize_loggers_with_handler(handler: logging.Handler):def _get_uvicorn_json_log_config():"""Generate a uvicorn log_config dictionary that applies JSON formatting to all loggers.-+This ensures that uvicorn's access logs, error logs, and all application logsare formatted as JSON when json_logs is enabled."""json_formatter_class = "litellm._logging.JsonFormatter"-+# Use the module-level log_level variable for consistencyuvicorn_log_level = log_level.upper()-+log_config = {"version": 1,"disable_existing_loggers": False,@@ -222,7 +302,7 @@ def _get_uvicorn_json_log_config():},},}-+return log_configdiff --git a/tests/test_litellm/test_logging.py b/tests/test_litellm/test_logging.pyindex 7e5931d8c0f..6f65ada7459 100644--- a/tests/test_litellm/test_logging.py+++ b/tests/test_litellm/test_logging.py@@ -1,27 +1,21 @@import asyncio-import datetimeimport jsonimport osimport sys-import unittest-from typing import List, Optional, Tuple-from unittest.mock import ANY, MagicMock, Mock, patch+from typing import List-import httpximport pytestsys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system-path-import ioimport loggingimport sys-import unittest-from contextlib import redirect_stdoutimport litellmfrom litellm._logging import (ALL_LOGGERS,+ JsonFormatter,_initialize_loggers_with_handler,_turn_on_json,verbose_logger,@@ -72,6 +66,117 @@ def test_json_mode_emits_one_record_per_logger(capfd):assert "timestamp" in obj, "`timestamp` key missing"+def test_json_formatter_parses_embedded_json_message():+ """+ Test that JsonFormatter parses embedded JSON in the message field and promotes+ sub-fields to first-class JSON properties for downstream querying.+ """+ formatter = JsonFormatter()+ record = logging.LogRecord(+ name="LiteLLM",+ level=logging.DEBUG,+ pathname="",+ lineno=0,+ msg='{"event": "giveup", "exception": "Connection failed", "model_name": "gpt-4"}',+ args=(),+ exc_info=None,+ )+ output = formatter.format(record)+ obj = json.loads(output)+ # Standard fields preserved+ assert "message" in obj+ assert obj["level"] == "DEBUG"+ assert "timestamp" in obj+ # Embedded JSON fields promoted to top-level for querying+ assert obj["event"] == "giveup"+ assert obj["exception"] == "Connection failed"+ assert obj["model_name"] == "gpt-4"+++def test_json_formatter_includes_extra_attributes():+ """+ Test that JsonFormatter includes extra attributes from logger.debug("msg", extra={...}).+ """+ formatter = JsonFormatter()+ record = logging.LogRecord(+ name="LiteLLM",+ level=logging.DEBUG,+ pathname="",+ lineno=0,+ msg="POST Request Sent from LiteLLM",+ args=(),+ exc_info=None,+ )+ record.api_base = "https://api.openai.com"+ record.authorization = "Bearer sk-***"+ output = formatter.format(record)+ obj = json.loads(output)+ assert obj["message"] == "POST Request Sent from LiteLLM"+ assert obj["api_base"] == "https://api.openai.com"+ assert obj["authorization"] == "Bearer sk-***"+++def test_json_formatter_plain_message_unchanged():+ """+ Test that non-JSON messages are passed through as-is in the message field.+ """+ formatter = JsonFormatter()+ record = logging.LogRecord(+ name="LiteLLM",+ level=logging.INFO,+ pathname="",+ lineno=0,+ msg="Cache hit!",+ args=(),+ exc_info=None,+ )+ output = formatter.format(record)+ obj = json.loads(output)+ assert obj["message"] == "Cache hit!"+ assert "event" not in obj+ assert "exception" not in obj+++def test_json_formatter_parses_embedded_python_dict_repr():+ """+ Test that JsonFormatter parses Python dict repr (str/deployment) embedded in+ plain text, e.g. from get_available_deployment logs.+ Reproduces Roni's reported case.+ """+ formatter = JsonFormatter()+ msg = (+ "get_available_deployment for model: text-embedding-3-large, "+ "Selected deployment: {'model_name': 'text-embedding-3-large', "+ "'litellm_params': {'api_key': 'sk**********', 'tpm': 1000000, 'rpm': 2000, "+ "'use_in_pass_through': False, 'use_litellm_proxy': False, "+ "'merge_reasoning_content_in_choices': False, 'model': 'text-embedding-3-large'}, "+ "'model_info': {'id': 'a624b057aec64ada48311', 'db_model': False}} "+ "for model: text-embedding-3-large"+ )+ record = logging.LogRecord(+ name="LiteLLM Router",+ level=logging.INFO,+ pathname="",+ lineno=0,+ msg=msg,+ args=(),+ exc_info=None,+ )+ output = formatter.format(record)+ obj = json.loads(output)+ assert "message" in obj+ assert obj["level"] == "INFO"+ # Python dict parsed and promoted to first-class properties+ assert obj["model_name"] == "text-embedding-3-large"+ assert "litellm_params" in obj+ assert obj["litellm_params"]["api_key"] == "sk**********"+ assert obj["litellm_params"]["tpm"] == 1000000+ assert obj["litellm_params"]["use_in_pass_through"] is False+ assert "model_info" in obj+ assert obj["model_info"]["id"] == "a624b057aec64ada48311"+ assert obj["model_info"]["db_model"] is False++def test_initialize_loggers_with_handler_sets_propagate_false():"""Test that the initialize_loggers_with_handler function sets propagate to False for all loggers@@ -96,7 +201,7 @@ async def test_cache_hit_includes_custom_llm_provider():test_custom_logger = CacheHitCustomLogger()original_callbacks = litellm.callbacks.copy() if litellm.callbacks else []litellm.callbacks = [test_custom_logger]-+try:# First call - should be a cache missresponse1 = await litellm.acompletion(@@ -105,10 +210,10 @@ async def test_cache_hit_includes_custom_llm_provider():mock_response="test response",caching=True,)-+# Wait for logging to completeawait asyncio.sleep(0.5)-+# Second identical call - should be a cache hitresponse2 = await litellm.acompletion(model="gpt-3.5-turbo",@@ -116,38 +221,43 @@ async def test_cache_hit_includes_custom_llm_provider():mock_response="test response",caching=True,)-+# Wait for logging to completeawait asyncio.sleep(0.5)-+# Verify we have logged events- assert len(test_custom_logger.logged_standard_logging_payloads) >= 2, \- f"Expected at least 2 logged events, got {len(test_custom_logger.logged_standard_logging_payloads)}"-+ assert (+ len(test_custom_logger.logged_standard_logging_payloads) >= 2+ ), f"Expected at least 2 logged events, got {len(test_custom_logger.logged_standard_logging_payloads)}"+# Find the cache hit event (should be the second call)cache_hit_payload = Nonefor payload in test_custom_logger.logged_standard_logging_payloads:if payload.get("cache_hit") is True:cache_hit_payload = payloadbreak-+# Verify cache hit event was found- assert cache_hit_payload is not None, "No cache hit event found in logged payloads"-+ assert (+ cache_hit_payload is not None+ ), "No cache hit event found in logged payloads"+# Verify custom_llm_provider is included in the cache hit payload- assert "custom_llm_provider" in cache_hit_payload, \- "custom_llm_provider missing from cache hit standard logging payload"-+ assert (+ "custom_llm_provider" in cache_hit_payload+ ), "custom_llm_provider missing from cache hit standard logging payload"+# Verify custom_llm_provider has a valid value (should be "openai" for gpt-3.5-turbo)custom_llm_provider = cache_hit_payload["custom_llm_provider"]- assert custom_llm_provider is not None and custom_llm_provider != "", \- f"custom_llm_provider should not be None or empty, got: {custom_llm_provider}"-+ assert (+ custom_llm_provider is not None and custom_llm_provider != ""+ ), f"custom_llm_provider should not be None or empty, got: {custom_llm_provider}"+print(f"Cache hit standard logging payload with custom_llm_provider: {custom_llm_provider}",json.dumps(cache_hit_payload, indent=2),)-+finally:# Clean uplitellm.callbacks = original_callbacks