Adding Logs to the Agent › Making Logs Useful

Michael BrenndoerferAugust 6, 20252 min read
AI Agent HandbookAll chapters
Part 12 of 15Observability and Debugging - Peering Inside the Agent
Chapter 33Adding Logs to the Agent › Making Logs Useful
Reading section 6 of 10 · Making Logs Useful · 2 minSection 6 of 10 · 2 min

Book contents

Section 6 of 10 · 2 min read

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:

In[12]:
Code
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.

In[13]:
Code
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.

In[6]:
Code
## 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.

In[14]:
Code
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}")