Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 67. Observability and tracing
  4. 67.1

Lesson 67.1 · 1 of 9 · 4 min read · Reviewed 24 Nov 2026

Traces, spans and what to log

By the end, you can

  • Describe a trace and its spans for one agent run.
  • Decide what to record on each span.

Logs tell you that something happened. A traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. tells you the story of one request, step by step.

Traces and spans

trace: support request #8841                      total 6.2 s
|- span: model call 1 (plan)          1.1 s   2,310 in / 180 out
|- span: tool lookup_order            0.4 s   ok
|- span: model call 2                 1.3 s   2,720 in / 95 out
|- span: tool issue_refund            0.2 s   error 503
|   |- span: retry 1                  0.3 s   ok
|- span: model call 3 (reply)         2.9 s   3,050 in / 410 out

Each span has a start, an end, a parent and attributes. Nested spans show retries and subagentsSubagent: A separate agent instance, with its own context and instructions, that a main agent delegates a task to. under the step that caused them.

What to record

On every span Why
Trace id, span id, parent id Stitch the run together
Start, duration, status Find slow or failed steps
Model id and settings Compare behaviour across versions
Input, output and cache token counts Cost and context growth
Tool name, arguments, result size See what the agent actually did
User, tenant, feature, prompt version Slice dashboards and find who is affected

Prompt and response text is the most useful and the most sensitive field. Lesson 67.3 covers how to keep it safely.

Use a standard

OpenTelemetryOpenTelemetry: An open standard and toolkit for collecting traces, metrics and logs from software. has semantic conventions for generative AI spans, so traces from different libraries and vendors line up in one tool. Using the standard names now saves a migration later.

Key points

  • A trace is one request end to end; spans are its steps: each model call, tool call, retry and handoff.
  • On every span record timing, status, model, token counts, cost and ids that link it to the user request.
  • Without traces, an agent that made twelve calls and gave a wrong answer is nearly impossible to debug.
Hands-on labRuns in the Playground

Turn flat spans into a trace waterfall

Rebuild one agent run from flat span records and read it as a story.

You will have: A script that prints an indented waterfall with timings, status and tokens, plus totals.

Steps

  1. Run the starter: it prints only the trace header.
  2. Write children_of() to group spans by parent id.
  3. Write render() so each span prints under its parent, one indent per level.
  4. Print total tokens and the names of failed spans.
  5. Check that the retry sits under the failed issue_refund call.

Done when

  • The retry span is indented under tool issue_refund.
  • Total tokens print as 8765.
  • The failed spans list contains only tool issue_refund.

Open in the Playground No API key needed.

Starter code (Python)
# Build a trace tree from flat spans and print it as a waterfall.
SPANS = [
    {"id": "s1", "parent": None, "name": "agent run", "ms": 6200, "status": "ok", "in": 0, "out": 0},
    {"id": "s2", "parent": "s1", "name": "model call 1 (plan)", "ms": 1100, "status": "ok", "in": 2310, "out": 180},
    {"id": "s3", "parent": "s1", "name": "tool lookup_order", "ms": 400, "status": "ok", "in": 0, "out": 0},
    {"id": "s4", "parent": "s1", "name": "model call 2", "ms": 1300, "status": "ok", "in": 2720, "out": 95},
    {"id": "s5", "parent": "s1", "name": "tool issue_refund", "ms": 200, "status": "error 503", "in": 0, "out": 0},
    {"id": "s6", "parent": "s5", "name": "retry 1", "ms": 300, "status": "ok", "in": 0, "out": 0},
    {"id": "s7", "parent": "s1", "name": "model call 3 (reply)", "ms": 2900, "status": "ok", "in": 3050, "out": 410},
]


def children_of(spans):
    """Map each parent id to its child spans, keeping their order."""
    # TODO: build a dict like {None: [root], "s1": [...], "s5": [retry]}
    return {}


def render(kids, parent=None, depth=0):
    """Return one line per span, indented under its parent."""
    lines = []
    # TODO: for each child of `parent`, add a line "|- name  1.1 s  status  tokens",
    # indented by depth, then add the lines of its own children (depth + 1).
    return lines


print("trace support-8841")
for line in render(children_of(SPANS)):
    print(line)
# TODO: print the total tokens (in + out) across all spans, and the names of failed spans.
Show a solution
# Build a trace tree from flat spans and print it as a waterfall.
SPANS = [
    {"id": "s1", "parent": None, "name": "agent run", "ms": 6200, "status": "ok", "in": 0, "out": 0},
    {"id": "s2", "parent": "s1", "name": "model call 1 (plan)", "ms": 1100, "status": "ok", "in": 2310, "out": 180},
    {"id": "s3", "parent": "s1", "name": "tool lookup_order", "ms": 400, "status": "ok", "in": 0, "out": 0},
    {"id": "s4", "parent": "s1", "name": "model call 2", "ms": 1300, "status": "ok", "in": 2720, "out": 95},
    {"id": "s5", "parent": "s1", "name": "tool issue_refund", "ms": 200, "status": "error 503", "in": 0, "out": 0},
    {"id": "s6", "parent": "s5", "name": "retry 1", "ms": 300, "status": "ok", "in": 0, "out": 0},
    {"id": "s7", "parent": "s1", "name": "model call 3 (reply)", "ms": 2900, "status": "ok", "in": 3050, "out": 410},
]


def children_of(spans):
    """Map each parent id to its child spans, keeping their order."""
    kids = {}
    for s in spans:
        kids.setdefault(s["parent"], []).append(s)
    return kids


def render(kids, parent=None, depth=0):
    """Return one line per span, indented under its parent."""
    lines = []
    for s in kids.get(parent, []):
        tokens = f"  {s['in']:,} in / {s['out']:,} out" if s["in"] else ""
        lines.append(f"{'    ' * depth}|- {s['name']:<22} {s['ms'] / 1000:.1f} s  {s['status']}{tokens}")
        lines += render(kids, s["id"], depth + 1)
    return lines


print("trace support-8841")
for line in render(children_of(SPANS)):
    print(line)
print("total tokens:", sum(s["in"] + s["out"] for s in SPANS))
print("failed spans:", [s["name"] for s in SPANS if s["status"] != "ok"])
Quick checkAn agent gave a wrong answer after nine tool calls. What lets you see which step went wrong?
How sure are you?
Pick an answer and how sure you are