Logging
Overview
This module provides structured logging for agents running in production environments. It follows best practices for: - JSON-structured logs for easy parsing - Separate development and production handlers - Event-based logging for analysis - Token usage and performance metrics - Container-friendly file handling
Usage Example
# Create an agent with production logging
agent = Agent(
role="production_agent",
model="gpt-4o",
tools=[solve_math],
log_dir="/var/log/cosma" # Production log directory
)
# Logs will include structured data
response = agent.run_with_tools("Calculate sqrt(16)")
# Log output example:
# {"timestamp": "2024-02-15T14:23:45",
# "event": "tool_call",
# "data": {"tool": "solve_math", "args": {"expression": "sqrt(16)"}}}Production Setup
For containerized environments: 1. Mount a volume for logs: /var/log/cosma 2. Set LOG_LEVEL environment variable 3. Configure log rotation (logrotate recommended)
AgentLogger
AgentLogger (name:str, level:int=20, log_dir:Optional[str]=None)
*Structured logging for agent activities with console and file output.
Args: name: Logger name (typically agent role) level: Logging level (default: INFO) log_dir: Optional directory for log files
Example: python logger = AgentLogger( name="math_agent", log_dir="logs" ) logger.log_event("tool_called", tool="solve_math", input="sqrt(16)", result=4.0 )*
AgentLogger.log_event
AgentLogger.log_event (event:str, **data)
*Log a structured event with arbitrary data.
Args: event: Type of event (e.g., ‘prompt_received’, ‘tool_called’) **data: Arbitrary key-value pairs for event data
Example: python logger.log_event('tool_called', tool_name='solve_math', input='sqrt(16)', result=4.0, execution_time=0.05 )*
AgentLogger.log_completion
AgentLogger.log_completion (chat_completion, execution_time:float)
*Log metrics from a chat completion response.
Args: chat_completion: Response from cosette Chat execution_time: Time taken for the complete interaction*
AgentLogger.log_metrics
AgentLogger.log_metrics (metrics:dict)
*Log accumulated metrics for the agent.
Args: metrics: Dictionary of metric names and values*
AgentMetrics
AgentMetrics (total_tokens:int=0, prompt_tokens:int=0, completion_tokens:int=0, tool_calls:int=0, total_time:float=0.0, successful_calls:int=0, failed_calls:int=0)
*Collect and track agent performance metrics.
Tracks: - Token usage - Tool calls - Response times - Success/failure rates*