Adding Logs to the Agent › Making Logs Useful
AI Agent HandbookAll chapters Adding Logs to the Agent › Making Logs UsefulOne section · Sections in this chapter6 / 10 ↓
Raw print statements can work for quick debugging, but structured logging makes your logs much more useful, especially when you're handling many requests or running the agent in production.
Include Timestamps: Knowing when each action happened helps you understand timing issues and correlate logs with user reports. The logging module adds timestamps automatically when you configure the format:
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s")Add Context: Include relevant identifiers in your logs so you can track a single request through the entire system. If your agent handles multiple users, log the user ID. If it processes multiple requests, log a request ID.
class PersonalAssistant:
def __init__(self, api_key, user_id):
self.user_id = user_id
self.logger = logging.getLogger(f"assistant.{user_id}")
def process_query(self, user_input, request_id):
self.logger.info(f"[Request {request_id}] Processing: {user_input}")Structure Your Messages: Use a consistent format for logs of the same type. This makes it easier to search through logs or process them automatically.
## Good: Consistent structure
logger.info(f"Tool called: {tool_name}, input: {input_data}")
logger.info(f"Tool completed: {tool_name}, result: {result}")
## Less useful: Inconsistent structure
logger.info(f"Using {tool_name}")
logger.info(f"Got back: {result}")Be Selective About Sensitive Data: Don't log sensitive information like passwords, API keys, or personal user data. If you need to log something that might contain sensitive data, redact it first.
def log_user_query(query):
# Redact emails from logs
safe_query = query.replace(
r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]"
)
logger.info(f"User query: {safe_query}")