Why Agents Need Traces, Not Just Logs
Compare flat log lines with traces for agent runs: model a run as a tree of spans, record token usage and latency on each span, and pass trace context to remote tools so their spans join the same trace.
Contentsand lesson path
On this page
- Why Flat Logs Fail for Multi-Step Agents
- Hierarchical Tracing: Modeling Agents as Trees of Spans
- Context Propagation Across External Boundaries and MCP
- Practice questions
- Apply it
- Review prompt
Lessons of Agent Tracing & Debugging
- Why Agents Need Traces, Not Just Logs Concept · 15 min
- Lab: Instrumenting the Loop with Spans Lab · 25 min
- Reading a Failed Trace Worked example · 20 min
- Building a Failure Taxonomy from 20 Runs Lab · 25 min
- Cost and Latency per Step Worked example · 15 min
- Check: Find the Faulty Step Knowledge check · 6 questions
What you will learn
- Instrument an agent with nested spans for runs, model calls and tool calls using the OpenTelemetry GenAI semantic conventions or an equivalent tracing SDK, with sensitive content redacted.
01. Why Flat Logs Fail for Multi-Step Agents
Many applications are debugged with log lines alone. In a typical web service, a request runs the same fixed sequence of handlers, database queries and cache lookups each time. When an error occurs, you filter the log by a request ID and read the lines in time order until you find the one that failed.
An agent run is harder to read this way. The model chooses the next step at run time, so two runs of the same task can take different paths, and a run can loop back on itself. One user request may lead to dozens of turns, parallel model calls, several tool calls, sub-agents and retries, all writing to the same log.
When an agent fails, or succeeds but is too slow or uses too many tokens, a flat log file is hard to interpret. Log lines alone make these questions hard to answer:
- Which tool call sent the agent down the wrong path?
- How many tokens, how much money and how much time went to the intermediate steps, and how much to writing the final answer?
- Why did turn 4 call tool B instead of tool C, and what exact prompt and history did the model see at that moment?
- Was the run slow because the model took long to start answering (time-to-first-token, TTFT), or because a tool waited on a locked database row?
Without a record of which turn started which model call and which tool call, the log is a long list of lines, and you have to rebuild the order of events by hand before you can find the cause.
02. Hierarchical Tracing: Modeling Agents as Trees of Spans
Distributed tracing answers these questions by recording a run as a tree of timed steps called spans. Each span has a start time, an end time and a parent. All the spans of one user request form a trace.
In an instrumented agent, the tree of spans follows the structure of the loop:
-
Agent span (
invoke_agent {agent name}, withgen_ai.operation.name = invoke_agent). It covers the whole user task and records the agent name and the total duration. When content capture is switched on, it can also hold the user input and the final output. Cost is not a convention attribute: you add it up from the token counts of the model spans below it. -
Turn spans (
agent.turn, a custom span that is not part of the conventions). Each one covers one cycle of the loop: a model call and the tool calls it asked for. Give it small, safe attributes such as the turn number and the number of messages in the history. Do not copy the conversation itself onto it: that text is content, so the same opt-in and masking rules apply as on the model span. -
Model spans (
chat {model}, for examplechat gpt-6-luna, span kind CLIENT,gen_ai.operation.name = chat). Each one records one request to the model provider: the provider, the requested and returned model names, input and output token counts, cached tokens, finish reasons and latency. Prompt and response text is opt-in under the conventions, because it often contains personal data. -
Tool spans (
execute_tool {tool name}, span kind INTERNAL,gen_ai.operation.name = execute_tool). Each one records one function call the model asked for: the tool name, the tool call ID, the duration and any error. When content capture is on, it also holds the arguments and the result returned to the model.
Because every span stores the id of its parent (parent_span_id), a tracing backend can draw the whole tree, and you can open the turn and the tool where an error or a delay started.
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class AgentSpan:
name: str
span_id: str
parent_id: Optional[str] = None
duration_ms: float = 0.0
attributes: Dict[str, Any] = field(default_factory=dict)
children: List["AgentSpan"] = field(default_factory=list)
# The agent execution tree, with span names from the GenAI conventions
# invoke_agent triage_agent (root; Task: "Triage ticket")
# ├── agent.turn 1 (custom span, not in the conventions)
# │ ├── chat gpt-6-luna (CLIENT; input+output tokens=460)
# │ └── execute_tool query_db (INTERNAL; 140 ms)
# └── agent.turn 2
# └── chat gpt-6-luna (CLIENT; input+output tokens=656)03. Context Propagation Across External Boundaries and MCP
Most agents do not run in one process. They call remote services, query Model Context Protocol (MCP) servers, hand subtasks to other agents and put work on message queues. A trace only stays in one piece if each call carries the caller's trace context to the other side. This is called context propagation.
The standard format is W3C Trace Context: a traceparent value and an optional tracestate value. traceparent has four fields, version-trace-id-parent-id-trace-flags, for example 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. The trace id names the whole trace. The parent id is the id of the span that was active in the caller when it sent the request: for a tool call made inside execute_tool search_docs, that span.
Where the context travels depends on the protocol. For a plain HTTP tool, the runtime puts traceparent in an HTTP header. If an HTTP client library adds its own CLIENT span around the request, that span is active instead and becomes the parent, and it still sits under execute_tool. For MCP, the OpenTelemetry MCP conventions put the context in the request's params._meta field instead, because one MCP request can span several HTTP requests (retries) and one HTTP stream can carry several MCP messages. The MCP client span, or the execute_tool span when the tool instrumentation adds the MCP attributes to it, is then the parent of the server span whatever the transport; an HTTP span is only recorded as a link.
When the remote tool server or MCP server receives the call, it extracts the context and starts its own spans as children of that parent span. If the server is instrumented and exports to the same backend, the trace viewer shows its work inside the agent's trace. For example, a slow query or a disk I/O error in an MCP database server appears nested under the tool call span that caused it.
The OpenTelemetry GenAI semantic conventions give these spans shared names. They are still in Development status. They now live in the separate semantic-conventions-genai repository, whose first release, v0.1.0, came out on 21 November 2026. Names can still change between releases (v0.1.0 itself renamed several), so note the release or commit you follow; this lesson follows v0.1.0. They define gen_ai.operation.name (chat, execute_tool, invoke_agent and others), gen_ai.provider.name (which replaced the deprecated gen_ai.system), gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, and span names such as chat gpt-6-luna and execute_tool query_db. Many backends (Langfuse, Arize Phoenix, Jaeger, Datadog and others) understand them, but how completely each one maps them varies, so check your backend before relying on a field.
Traces also need care with data. They often hold what users typed and records read from your databases, so remove or mask personal data (personally identifiable information, PII) before spans leave your systems. Sampling keeps storage costs in check. Head-based sampling decides when a trace starts, so it cannot know whether the run will fail. Tail-based sampling decides after the trace is complete, so it can keep the runs that matter most: errors, tool failures and latency outliers.
04. Practice questions
05. Apply it
Try these on an agent you run:
- Give every run an agent span, one span per turn, and a child span for each model call and each tool call.
- On model spans, set
gen_ai.operation.name,gen_ai.provider.name,gen_ai.request.model,gen_ai.usage.input_tokensandgen_ai.usage.output_tokens, and write down the release of the conventions you follow. - Pass trace context on every remote call: put
traceparentin an HTTP header for plain HTTP tools, and inparams._metafor MCP requests, so the remote spans nest under the agent trace. - Record prompts and tool arguments only where your data policy allows it, and redact them first. They show what the model saw when you debug a failure, but re-sending them will not reproduce the same output exactly.
- Keep model time, including time to first token, apart from tool time, so you can see which one makes a slow run slow.
06. Review prompt
In your own words, explain why a time-ordered log makes it hard to find which step of an agent run caused a failure, and what the parent id of a span adds. Then sketch the span tree of a two-turn run with one tool call, and explain how traceparent lets the spans of an MCP server join that tree.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.