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
Add log_format parameter to GenericAPILogger (#18587)
Chetan Choudhary687adc60241e
diff --git a/docs/my-website/docs/observability/generic_api.md b/docs/my-website/docs/observability/generic_api.mdindex 2d1a24c317b..93a0762591a 100644--- a/docs/my-website/docs/observability/generic_api.md+++ b/docs/my-website/docs/observability/generic_api.md@@ -47,6 +47,7 @@ callback_settings:| `endpoint` | string | Yes | HTTP endpoint to send logs to || `headers` | dict | No | Custom headers for the request || `event_types` | list | No | Filter events: `llm_api_success`, `llm_api_failure`. Defaults to all events. |+| `log_format` | string | No | Output format: `json_array` (default), `ndjson`, or `single`. Controls how logs are batched and sent. |## Pre-configured Callbacks@@ -107,4 +108,62 @@ callback_settings:flush_interval: 60 # seconds, default: 60```+## Log Format Options++Control how logs are formatted and sent to your endpoint.++### JSON Array (Default)++```yaml+callback_settings:+ my_api:+ callback_type: generic_api+ endpoint: https://your-endpoint.com+ log_format: json_array # default if not specified+```++Sends all logs in a batch as a single JSON array `[{log1}, {log2}, ...]`. This is the default behavior and maintains backward compatibility.++**When to use**: Most HTTP endpoints expecting batched JSON data.++### NDJSON (Newline-Delimited JSON)++```yaml+callback_settings:+ my_api:+ callback_type: generic_api+ endpoint: https://your-endpoint.com+ log_format: ndjson+```++Sends logs as newline-delimited JSON (one record per line):+```+{log1}+{log2}+{log3}+```++**When to use**: Log aggregation services like Sumo Logic, Splunk, or Datadog that support field extraction on individual records.++**Benefits**:+- Each log is ingested as a separate message+- Field Extraction Rules work at ingest time+- Better parsing and querying performance++### Single++```yaml+callback_settings:+ my_api:+ callback_type: generic_api+ endpoint: https://your-endpoint.com+ log_format: single+```++Sends each log as an individual HTTP request in parallel when the batch is flushed.++**When to use**: Endpoints that expect individual records, or when you need maximum compatibility.++**Note**: This mode sends N HTTP requests per batch (more overhead). Consider using `ndjson` instead if your endpoint supports it.+diff --git a/docs/my-website/docs/observability/sumologic_integration.md b/docs/my-website/docs/observability/sumologic_integration.mdindex d0894146e4c..c30ee94dad4 100644--- a/docs/my-website/docs/observability/sumologic_integration.md+++ b/docs/my-website/docs/observability/sumologic_integration.md@@ -148,6 +148,51 @@ Example payload:## Advanced Configuration+### Log Format++The Sumo Logic integration uses **NDJSON (newline-delimited JSON)** format by default. This format is optimal for Sumo Logic's parsing capabilities and allows Field Extraction Rules to work at ingest time.++#### NDJSON Format++Each log entry is sent as a separate line in the HTTP request:+```+{"id":"chatcmpl-1","model":"gpt-3.5-turbo","response_cost":0.0001,...}+{"id":"chatcmpl-2","model":"gpt-4","response_cost":0.0003,...}+{"id":"chatcmpl-3","model":"gpt-3.5-turbo","response_cost":0.0001,...}+```++#### Benefits for Field Extraction Rules (FERs)++With NDJSON format, you can create Field Extraction Rules directly:++```+_sourceCategory=litellm/logs+| json field=_raw "model", "response_cost", "user" as model, cost, user+```++**Before NDJSON** (with JSON array format):+- Required `parse regex ... multi` workaround+- FERs couldn't parse at ingest time+- Query-time parsing impacted dashboard performance++**After NDJSON**:+- ✅ FERs parse fields at ingest time+- ✅ No query-time workarounds needed+- ✅ Better dashboard performance+- ✅ Simpler query syntax++#### Changing the Log Format (Advanced)++If you need to change the log format (not recommended for Sumo Logic):++```yaml+callback_settings:+ sumologic:+ callback_type: generic_api+ callback_name: sumologic+ log_format: json_array # Override to use JSON array instead+```+### Batching SettingsControl how LiteLLM batches logs before sending to Sumo Logic:diff --git a/litellm/integrations/generic_api/generic_api_callback.py b/litellm/integrations/generic_api/generic_api_callback.pyindex 1c8a5b883da..1c62ce9fcc3 100644--- a/litellm/integrations/generic_api/generic_api_callback.py+++ b/litellm/integrations/generic_api/generic_api_callback.py@@ -25,6 +25,7 @@ from litellm.llms.custom_httpx.http_handler import (from litellm.types.utils import StandardLoggingPayloadAPI_EVENT_TYPES = Literal["llm_api_success", "llm_api_failure"]+LOG_FORMAT_TYPES = Literal["json_array", "ndjson", "single"]def load_compatible_callbacks() -> Dict:@@ -101,6 +102,7 @@ class GenericAPILogger(CustomBatchLogger):headers: Optional[dict] = None,event_types: Optional[List[API_EVENT_TYPES]] = None,callback_name: Optional[str] = None,+ log_format: Optional[LOG_FORMAT_TYPES] = None,**kwargs,):"""@@ -111,6 +113,7 @@ class GenericAPILogger(CustomBatchLogger):headers: Optional[dict] = None,event_types: Optional[List[API_EVENT_TYPES]] = None,callback_name: Optional[str] = None - If provided, loads config from generic_api_compatible_callbacks.json+ log_format: Optional[LOG_FORMAT_TYPES] = None - Format for log output: "json_array" (default), "ndjson", or "single""""########################################################## Check if callback_name is provided and load config@@ -135,6 +138,9 @@ class GenericAPILogger(CustomBatchLogger):if event_types is None and "event_types" in callback_config:event_types = callback_config["event_types"]++ if log_format is None and "log_format" in callback_config:+ log_format = callback_config["log_format"]else:verbose_logger.warning(f"callback_name '{callback_name}' not found in generic_api_compatible_callbacks.json"@@ -156,8 +162,16 @@ class GenericAPILogger(CustomBatchLogger):self.endpoint: str = endpointself.event_types: Optional[List[API_EVENT_TYPES]] = event_typesself.callback_name: Optional[str] = callback_name++ # Validate and store log_format+ if log_format is not None and log_format not in ["json_array", "ndjson", "single"]:+ raise ValueError(+ f"Invalid log_format: {log_format}. Must be one of: 'json_array', 'ndjson', 'single'"+ )+ self.log_format: LOG_FORMAT_TYPES = log_format or "json_array"+verbose_logger.debug(- f"in init GenericAPILogger, callback_name: {self.callback_name}, endpoint {self.endpoint}, headers {self.headers}, event_types: {self.event_types}"+ f"in init GenericAPILogger, callback_name: {self.callback_name}, endpoint {self.endpoint}, headers {self.headers}, event_types: {self.event_types}, log_format: {self.log_format}")#########################################################@@ -289,25 +303,65 @@ class GenericAPILogger(CustomBatchLogger):async def async_send_batch(self):"""Sends the batch of messages to Generic API Endpoint++ Supports three formats:+ - json_array: Sends all logs as a JSON array (default)+ - ndjson: Sends logs as newline-delimited JSON+ - single: Sends each log as individual HTTP request in parallel"""try:if not self.log_queue:returnverbose_logger.debug(- f"Generic API Logger - about to flush {len(self.log_queue)} events"+ f"Generic API Logger - about to flush {len(self.log_queue)} events in '{self.log_format}' format")- # make POST request to Generic API Endpoint- response = await self.async_httpx_client.post(- url=self.endpoint,- headers=self.headers,- data=safe_dumps(self.log_queue),- )+ if self.log_format == "single":+ # Send each log as individual HTTP request in parallel+ tasks = []+ for log_entry in self.log_queue:+ task = self.async_httpx_client.post(+ url=self.endpoint,+ headers=self.headers,+ data=safe_dumps(log_entry),+ )+ tasks.append(task)++ # Execute all requests in parallel+ responses = await asyncio.gather(*tasks, return_exceptions=True)++ # Log results+ for idx, result in enumerate(responses):+ if isinstance(result, Exception):+ verbose_logger.exception(+ f"Generic API Logger - Error sending log {idx}: {result}"+ )+ else:+ # result is a Response object+ verbose_logger.debug(+ f"Generic API Logger - sent log {idx}, status: {result.status_code}" # type: ignore+ )+ else:+ # Format the payload based on log_format+ if self.log_format == "json_array":+ data = safe_dumps(self.log_queue)+ elif self.log_format == "ndjson":+ data = "\n".join(safe_dumps(log) for log in self.log_queue)+ else:+ raise ValueError(f"Unknown log_format: {self.log_format}")++ # Make POST request+ response = await self.async_httpx_client.post(+ url=self.endpoint,+ headers=self.headers,+ data=data,+ )- verbose_logger.debug(- f"Generic API Logger - sent batch to {self.endpoint}, status code {response.status_code}"- )+ verbose_logger.debug(+ f"Generic API Logger - sent batch to {self.endpoint}, "+ f"status: {response.status_code}, format: {self.log_format}"+ )except Exception as e:verbose_logger.exception(diff --git a/litellm/integrations/generic_api/generic_api_compatible_callbacks.json b/litellm/integrations/generic_api/generic_api_compatible_callbacks.jsonindex 6c8e5fd1b2a..12dc4ae643c 100644--- a/litellm/integrations/generic_api/generic_api_compatible_callbacks.json+++ b/litellm/integrations/generic_api/generic_api_compatible_callbacks.json@@ -22,6 +22,7 @@"headers": {"Content-Type": "application/json"},- "environment_variables": ["SUMOLOGIC_WEBHOOK_URL"]+ "environment_variables": ["SUMOLOGIC_WEBHOOK_URL"],+ "log_format": "ndjson"}}\ No newline at end of filediff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.pyindex b78484816da..4f76a5bad03 100644--- a/litellm/litellm_core_utils/logging_callback_manager.py+++ b/litellm/litellm_core_utils/logging_callback_manager.py@@ -166,6 +166,7 @@ class LoggingCallbackManager:endpoint = callback_config.get("endpoint")headers = callback_config.get("headers")event_types = callback_config.get("event_types")+ log_format = callback_config.get("log_format")if endpoint is None or headers is None:verbose_logger.warning(@@ -180,6 +181,7 @@ class LoggingCallbackManager:and cached_logger.endpoint == endpointand cached_logger.headers == headersand cached_logger.event_types == event_types+ and cached_logger.log_format == log_format):return cached_logger@@ -187,6 +189,7 @@ class LoggingCallbackManager:endpoint=endpoint,headers=headers,event_types=event_types,+ log_format=log_format,)_generic_api_logger_cache[callback] = new_loggerreturn new_loggerdiff --git a/tests/logging_callback_tests/test_generic_api_callback.py b/tests/logging_callback_tests/test_generic_api_callback.pyindex 3ddf84f2939..c3e1171e96a 100644--- a/tests/logging_callback_tests/test_generic_api_callback.py+++ b/tests/logging_callback_tests/test_generic_api_callback.py@@ -207,3 +207,253 @@ async def test_generic_api_callback_multiple_logs():assert (payload_item["response"]["choices"][0]["message"]["content"] == "hi"), "Response should be hi"+++async def test_generic_api_callback_ndjson_format():+ """+ Test the GenericAPILogger callback with ndjson log format.+ Validates that logs are sent as newline-delimited JSON.+ """+ # Create a mock for the async_httpx_client's post method+ mock_post = AsyncMock()+ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Set up an endpoint for testing+ test_endpoint = "https://example.com/api/logs"+ test_headers = {"Authorization": "Bearer test_token"}+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint++ # Initialize the GenericAPILogger with ndjson format+ generic_logger = GenericAPILogger(+ endpoint=test_endpoint,+ headers=test_headers,+ flush_interval=1,+ log_format="ndjson" # Set NDJSON format+ )+ generic_logger.async_httpx_client.post = mock_post+ litellm.callbacks = [generic_logger]++ # Make multiple completion calls to generate multiple logs+ for i in range(3):+ response = await litellm.acompletion(+ model="gpt-4o",+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],+ mock_response="hi",+ user="test_user",+ )++ # Wait for async flush+ await asyncio.sleep(3)++ # Assert httpx post was called+ mock_post.assert_called_once()++ # Get the actual request body from the mock+ actual_url = mock_post.call_args[1]["url"]+ assert actual_url == test_endpoint, f"Expected URL {test_endpoint}, got {actual_url}"++ # Get the data sent+ ndjson_data = mock_post.call_args[1]["data"]+ print("##########\n")+ print("ndjson_data:", ndjson_data)+ print("##########\n")++ # Validate it's NDJSON format (newline-delimited)+ assert isinstance(ndjson_data, str), "Data should be a string for NDJSON"++ # Split by newlines and parse each line+ lines = ndjson_data.strip().split("\n")+ assert len(lines) == 3, f"Expected 3 lines of NDJSON, got {len(lines)}"++ # Validate each line is valid JSON+ for i, line in enumerate(lines):+ payload_item = json.loads(line)+ payload_item = StandardLoggingPayload(**payload_item)++ # Basic assertions+ assert payload_item["response_cost"] > 0, "Response cost should be greater than 0"+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"+ assert payload_item["model_parameters"]["user"] == "test_user", "User should be test_user"+++async def test_generic_api_callback_single_format():+ """+ Test the GenericAPILogger callback with single log format.+ Validates that each log is sent as an individual request in parallel.+ """+ # Create a mock for the async_httpx_client's post method+ mock_post = AsyncMock()+ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Set up an endpoint for testing+ test_endpoint = "https://example.com/api/logs"+ test_headers = {"Authorization": "Bearer test_token"}+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint++ # Initialize the GenericAPILogger with single format+ generic_logger = GenericAPILogger(+ endpoint=test_endpoint,+ headers=test_headers,+ flush_interval=1, # Quick flush to trigger batch send+ log_format="single" # Set single format+ )+ generic_logger.async_httpx_client.post = mock_post+ litellm.callbacks = [generic_logger]++ # Make 3 completion calls+ for i in range(3):+ response = await litellm.acompletion(+ model="gpt-4o",+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],+ mock_response="hi",+ user="test_user",+ )++ # Wait for async flush+ await asyncio.sleep(3)++ # Assert httpx post was called 3 times (once per log in batch)+ assert mock_post.call_count == 3, f"Expected 3 calls, got {mock_post.call_count}"++ # Validate each call sent a single log object (not an array)+ for call_idx in range(3):+ call_args = mock_post.call_args_list[call_idx]+ json_data = call_args[1]["data"]++ print(f"########## Call {call_idx} ##########")+ print("json_data:", json_data)++ # Parse and validate - should be a single object, not an array+ actual_request = json.loads(json_data)+ assert isinstance(actual_request, dict), f"Call {call_idx}: Expected dict, got {type(actual_request)}"++ # Validate it's a valid StandardLoggingPayload+ payload_item = StandardLoggingPayload(**actual_request)+ assert payload_item["response_cost"] > 0, "Response cost should be greater than 0"+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"+++async def test_generic_api_callback_json_array_format_explicit():+ """+ Test the GenericAPILogger callback with explicit json_array format.+ Validates backward compatibility when explicitly set to json_array.+ """+ # Create a mock for the async_httpx_client's post method+ mock_post = AsyncMock()+ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Set up an endpoint for testing+ test_endpoint = "https://example.com/api/logs"+ test_headers = {"Authorization": "Bearer test_token"}+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint++ # Initialize the GenericAPILogger with explicit json_array format+ generic_logger = GenericAPILogger(+ endpoint=test_endpoint,+ headers=test_headers,+ flush_interval=1,+ log_format="json_array" # Explicitly set json_array+ )+ generic_logger.async_httpx_client.post = mock_post+ litellm.callbacks = [generic_logger]++ # Make multiple completion calls+ for i in range(5):+ response = await litellm.acompletion(+ model="gpt-4o",+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],+ mock_response="hi",+ user="test_user",+ )++ # Wait for async flush+ await asyncio.sleep(3)++ # Assert httpx post was called once (batched)+ mock_post.assert_called_once()++ # Get the data and validate it's a JSON array+ json_data = mock_post.call_args[1]["data"]+ actual_request = json.loads(json_data)++ assert isinstance(actual_request, list), "Request body should be a list (JSON array)"+ assert len(actual_request) == 5, f"Expected 5 items, got {len(actual_request)}"++ # Validate each item+ for payload_item in actual_request:+ payload_item = StandardLoggingPayload(**payload_item)+ assert payload_item["response_cost"] > 0, "Response cost should be greater than 0"+ assert payload_item["model"] == "gpt-4o", "Model should be gpt-4o"+++async def test_generic_api_callback_sumologic_uses_ndjson():+ """+ Test that the sumologic callback uses ndjson format by default+ when loaded from generic_api_compatible_callbacks.json+ """+ # Create a mock for the async_httpx_client's post method+ mock_post = AsyncMock()+ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Set environment variable for sumologic+ os.environ["SUMOLOGIC_WEBHOOK_URL"] = "https://collectors.sumologic.com/receiver/v1/http/test123"++ # Initialize using callback_name (loads from JSON config)+ generic_logger = GenericAPILogger(+ callback_name="sumologic",+ flush_interval=1+ )+ generic_logger.async_httpx_client.post = mock_post+ litellm.callbacks = [generic_logger]++ # Verify the logger has ndjson format+ assert generic_logger.log_format == "ndjson", "Sumologic should use ndjson format"++ # Make completion calls+ for i in range(2):+ await litellm.acompletion(+ model="gpt-4o",+ messages=[{"role": "user", "content": f"Test {i}"}],+ mock_response="response",+ user="test_user",+ )++ # Wait for async flush+ await asyncio.sleep(3)++ # Assert httpx post was called+ mock_post.assert_called_once()++ # Verify NDJSON format+ ndjson_data = mock_post.call_args[1]["data"]+ assert isinstance(ndjson_data, str), "Data should be a string for NDJSON"++ lines = ndjson_data.strip().split("\n")+ assert len(lines) == 2, f"Expected 2 lines of NDJSON, got {len(lines)}"++ # Each line should be valid JSON+ for line in lines:+ json.loads(line) # Will raise if invalid JSON+++async def test_generic_api_callback_invalid_log_format():+ """+ Test that invalid log_format values raise a ValueError+ """+ test_endpoint = "https://example.com/api/logs"+ os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint++ with pytest.raises(ValueError, match="Invalid log_format"):+ GenericAPILogger(+ endpoint=test_endpoint,+ log_format="invalid_format" # type: ignore # Intentionally invalid for testing+ )