本文介绍 Agent 的日志记录和可观测性建设,包括结构化日志、追踪、指标收集。
生产环境的 Agent 需要完善的监控体系。
import structlog
structlog.configure(
processors=[structlog.processors.JSONRenderer()]
)
logger = structlog.get_logger()
logger.info("tool_called",
tool="get_weather",
args={"location": "Beijing"},
agent_id="agent_001",
trace_id="trace_xxx"
)
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("agent_run") as span:
span.set_attribute("agent.id", agent_id)
result = agent.run(task)
span.set_attribute("task.completed", True)
from prometheus_client import Counter, Histogram
tool_calls = Counter('agent_tool_calls', 'Tool calls', ['tool_name'])
agent_duration = Histogram('agent_run_duration', 'Agent run duration')
可观测性方案验证通过