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: ensure audit log callbacks fire even when DB is unavailable
yuneng-jiang364f5c6e03df
diff --git a/litellm/proxy/management_helpers/audit_logs.py b/litellm/proxy/management_helpers/audit_logs.pyindex dee7c82ee52..a26a38bc4cd 100644--- a/litellm/proxy/management_helpers/audit_logs.py+++ b/litellm/proxy/management_helpers/audit_logs.py@@ -68,6 +68,18 @@ def _build_audit_log_payload()+def _audit_log_task_done_callback(task: asyncio.Task) -> None:+ """Log exceptions from audit log callback tasks so they don't slip through silently."""+ try:+ exc = task.exception()+ except asyncio.CancelledError:+ return+ if exc is not None:+ verbose_proxy_logger.error(+ "Audit log callback task failed: %s", exc, exc_info=exc+ )++async def _dispatch_audit_log_to_callbacks(request_data: LiteLLM_AuditLogs,) -> None:@@ -89,7 +101,10 @@ async def _dispatch_audit_log_to_callbacks(continueif isinstance(resolved, CustomLogger):- asyncio.create_task(resolved.async_log_audit_log_event(payload))+ task = asyncio.create_task(+ resolved.async_log_audit_log_event(payload)+ )+ task.add_done_callback(_audit_log_task_done_callback)except Exception as e:verbose_proxy_logger.error("Failed dispatching audit log to callback: %s", e@@ -160,9 +175,6 @@ async def create_audit_log_for_update(request_data: LiteLLM_AuditLogs):if premium_user is not True:return- if prisma_client is None:- raise Exception("prisma_client is None, no DB connected")-verbose_proxy_logger.debug("creating audit log for %s", request_data)if isinstance(request_data.updated_values, dict):@@ -171,6 +183,15 @@ async def create_audit_log_for_update(request_data: LiteLLM_AuditLogs):if isinstance(request_data.before_value, dict):request_data.before_value = json.dumps(request_data.before_value)+ # Dispatch to external audit log callbacks regardless of DB availability+ await _dispatch_audit_log_to_callbacks(request_data)++ if prisma_client is None:+ verbose_proxy_logger.error(+ "prisma_client is None, cannot write audit log to DB"+ )+ return+_request_data = request_data.model_dump(exclude_none=True)try:@@ -182,6 +203,3 @@ async def create_audit_log_for_update(request_data: LiteLLM_AuditLogs):except Exception as e:# [Non-Blocking Exception. Do not allow blocking LLM API call]verbose_proxy_logger.error(f"Failed Creating audit log {e}")-- # Dispatch to external audit log callbacks- await _dispatch_audit_log_to_callbacks(request_data)diff --git a/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py b/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.pyindex cfdf6ac0330..85eda4368cd 100644--- a/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py+++ b/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py@@ -15,6 +15,7 @@ import litellmfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.proxy._types import LiteLLM_AuditLogs, LitellmTableNamesfrom litellm.proxy.management_helpers.audit_logs import (+ _audit_log_task_done_callback,_build_audit_log_payload,_dispatch_audit_log_to_callbacks,create_audit_log_for_update,@@ -201,6 +202,80 @@ class TestCreateAuditLogForUpdateWithCallbacks:mock_logger.async_log_audit_log_event.assert_not_called()+ @pytest.mark.asyncio+ async def test_dispatches_even_when_prisma_client_is_none(self):+ """Callbacks should fire even if DB is unavailable."""+ mock_logger = MagicMock(spec=CustomLogger)+ mock_logger.async_log_audit_log_event = AsyncMock()+ litellm.audit_log_callbacks = [mock_logger]++ with patch("litellm.proxy.proxy_server.premium_user", True), patch(+ "litellm.store_audit_logs", True+ ), patch("litellm.proxy.proxy_server.prisma_client", None):+ audit_log = _make_audit_log()+ await create_audit_log_for_update(audit_log)+ await asyncio.sleep(0.1)++ # Callback should still be called despite no DB+ mock_logger.async_log_audit_log_event.assert_called_once()++ @pytest.mark.asyncio+ async def test_dispatches_even_when_db_write_fails(self):+ """Callbacks should fire even if the DB write raises."""+ mock_logger = MagicMock(spec=CustomLogger)+ mock_logger.async_log_audit_log_event = AsyncMock()+ litellm.audit_log_callbacks = [mock_logger]++ with patch("litellm.proxy.proxy_server.premium_user", True), patch(+ "litellm.store_audit_logs", True+ ), patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:+ mock_prisma.db.litellm_auditlog.create = AsyncMock(+ side_effect=RuntimeError("DB connection lost")+ )++ audit_log = _make_audit_log()+ await create_audit_log_for_update(audit_log)+ await asyncio.sleep(0.1)++ # Callback should still be called despite DB failure+ mock_logger.async_log_audit_log_event.assert_called_once()+++class TestAuditLogTaskDoneCallback:+ def test_logs_exception_from_failed_task(self):+ """Done callback should log task exceptions."""+ mock_task = MagicMock(spec=asyncio.Task)+ mock_task.exception.return_value = RuntimeError("callback failed")++ with patch(+ "litellm.proxy.management_helpers.audit_logs.verbose_proxy_logger"+ ) as mock_logger:+ _audit_log_task_done_callback(mock_task)+ mock_logger.error.assert_called_once()+ assert "callback failed" in str(mock_logger.error.call_args)++ def test_no_log_on_success(self):+ """Done callback should not log when task succeeds."""+ mock_task = MagicMock(spec=asyncio.Task)+ mock_task.exception.return_value = None++ with patch(+ "litellm.proxy.management_helpers.audit_logs.verbose_proxy_logger"+ ) as mock_logger:+ _audit_log_task_done_callback(mock_task)+ mock_logger.error.assert_not_called()++ def test_handles_cancelled_task(self):+ """Done callback should handle cancelled tasks gracefully."""+ mock_task = MagicMock(spec=asyncio.Task)+ mock_task.exception.side_effect = asyncio.CancelledError()++ with patch(+ "litellm.proxy.management_helpers.audit_logs.verbose_proxy_logger"+ ) as mock_logger:+ _audit_log_task_done_callback(mock_task)+ mock_logger.error.assert_not_called()+class TestS3LoggerAuditLogEvent:@pytest.mark.asyncio