How to Enable Logging for Requests and Responses in the Anthropic Python SDK
Set the ANTHROPIC_LOG environment variable to debug before importing the SDK to capture full HTTP request and response details.
The anthropics/anthropic-sdk-python repository provides a built-in logging helper that automatically emits detailed debug information for every API call. When you enable logging for requests and responses, you gain visibility into the raw HTTP traffic, headers, and payload data flowing between your application and Anthropic's API endpoints.
How the SDK Logging System Works
The Anthropic SDK implements a centralized logging configuration that reads from environment variables during package initialization. The core logic resides in src/anthropic/_utils/_logs.py, where the setup_logging() function configures Python's standard logging module. This function is automatically invoked when you import the anthropic package via src/anthropic/__init__.py.
The system recognizes two primary log levels:
debug: Enables DEBUG level for both theanthropicSDK logger and the underlyinghttpxHTTP client logger, printing complete request and response data including headers and bodies.info: Enables INFO level for the same loggers, providing less verbose output focused on request URLs and status codes.
Method 1: Enable Logging via Environment Variable
The simplest approach to enable logging for requests and responses is setting the environment variable before importing the SDK. This ensures the logging configuration is applied during package initialization.
import os
# Enable full request/response debugging
os.environ["ANTHROPIC_LOG"] = "debug"
import anthropic # Logging is configured during this import
client = anthropic.Anthropic()
# All subsequent API calls will emit detailed logs
response = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
When running this code, you will see output similar to:
[2024-07-15 12:34:56 - anthropic._base_client - DEBUG] HTTP Request: POST https://api.anthropic.com/v1/messages
[2024-07-15 12:34:57 - httpx - DEBUG] HTTP Response: 200 OK (text/event-stream)
Method 2: Programmatic Configuration
If you need to enable logging dynamically without relying on environment variables, you can invoke the setup_logging() function directly from anthropic._utils._logs. This approach is useful when building applications that need to toggle logging based on runtime configuration.
import os
import anthropic
from anthropic._utils._logs import setup_logging
# Set the environment variable programmatically
os.environ["ANTHROPIC_LOG"] = "debug"
# Manually trigger the logging setup
setup_logging()
# Now initialize the client
client = anthropic.Anthropic()
# Your API calls will now be logged
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=512,
messages=[{"role": "user", "content": "Explain logging"}],
)
Note that you must call setup_logging() after setting the environment variable but before creating API calls, as the function reads ANTHROPIC_LOG at invocation time.
Method 3: Custom Log Handlers and File Output
For production environments, you may want to capture request and response logs to a file rather than stdout, or integrate with existing logging infrastructure. Since the Anthropic SDK uses Python's standard logging module, you can attach custom handlers to the anthropic and httpx loggers.
import logging
import os
# Enable debug logging
os.environ["ANTHROPIC_LOG"] = "debug"
from anthropic._utils._logs import setup_logging
setup_logging()
# Retrieve the SDK logger
sdk_logger = logging.getLogger("anthropic")
http_logger = logging.getLogger("httpx")
# Prevent duplicate console output if desired
sdk_logger.propagate = False
http_logger.propagate = False
# Create file handler for persistent logging
file_handler = logging.FileHandler("anthropic_api.log")
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
file_handler.setFormatter(formatter)
# Attach to both loggers
sdk_logger.addHandler(file_handler)
http_logger.addHandler(file_handler)
import anthropic
client = anthropic.Anthropic()
# All request/response data will now be written to anthropic_api.log
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=256,
messages=[{"role": "user", "content": "Log this request"}],
)
This approach gives you full control over log formatting, rotation, and destination while maintaining the detailed request and response data provided by the SDK's debug mode.
Understanding Log Output Components
When you enable logging for requests and responses, the output contains two distinct logger streams:
-
anthropiclogger: Emits SDK-specific events including request preparation, retry attempts, and deserialization. Insrc/anthropic/_base_client.py, the client logs the HTTP method, URL, and headers at the DEBUG level before sending requests. -
httpxlogger: Emits low-level HTTP transport details including raw response headers, status codes, and body content. This is particularly useful for debugging connection issues or examining exact API responses.
Both loggers respect the level set via ANTHROPIC_LOG, ensuring consistent verbosity across the entire request lifecycle.
Summary
- Set the
ANTHROPIC_LOGenvironment variable todebugbefore importing the Anthropic SDK to enable detailed request and response logging. - The logging configuration is handled by
setup_logging()insrc/anthropic/_utils/_logs.pyand executed automatically during package import viasrc/anthropic/__init__.py. - Use
debuglevel for full HTTP body and header details, orinfofor less verbose output showing only URLs and status codes. - For custom logging destinations, attach handlers to the
anthropicandhttpxloggers after callingsetup_logging().
Frequently Asked Questions
What environment variable controls logging in the Anthropic SDK?
The ANTHROPIC_LOG environment variable controls logging behavior. Set it to debug or info before importing the anthropic package to enable request and response logging. The SDK reads this variable during initialization in src/anthropic/__init__.py and configures the appropriate log levels via src/anthropic/_utils/_logs.py.
Can I enable logging after importing the Anthropic SDK?
Yes, but you must manually invoke the setup function. If you have already imported the SDK without setting ANTHROPIC_LOG, you can still enable logging by setting the environment variable and then calling anthropic._utils._logs.setup_logging(). However, for best results, configure logging before creating any client instances to ensure all HTTP traffic is captured.
What is the difference between debug and info logging levels?
The debug level enables the most verbose output, logging complete HTTP request and response bodies, headers, and detailed SDK internal operations through both the anthropic and httpx loggers. The info level provides a lighter view, logging only essential information such as request URLs, HTTP methods, and response status codes without full body content, making it suitable for production monitoring without exposing sensitive data.
How do I save Anthropic SDK logs to a file instead of the console?
Since the SDK uses Python's standard logging module, you can attach a FileHandler to the anthropic and httpx loggers. First, enable logging via ANTHROPIC_LOG=debug and call setup_logging(). Then retrieve the loggers using logging.getLogger("anthropic") and logging.getLogger("httpx"), create a FileHandler with your desired filename, and attach it to both loggers. This captures all request and response data to your specified file while optionally suppressing console output by setting logger.propagate = False.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →