# Observability
<!--
ref: @protocol/observability
type: protocol
tags: [observability, debugging, monitoring, tracing, logging]
triggers: [debugging issues, monitoring performance, analyzing agent behavior]
trigger_prompt: When you need to understand what happened during an agent run, identify failures, or track performance trends over time.
category: verify
last_reviewed: 2026-04-30
complements: [@protocol/eval, @protocol/agent-shipping, @protocol/devloop, @protocol/loop]
audience: [agent-author, claude-code-user, openclaw-user, terminal-only]
version: 6
updated_at: 2026-07-14T23:24:02.938Z
-->

Implement observability to track and analyze agent runs through traces, logs, and metrics.

Observability is the alternative. It means you have a record of exactly what happened — every tool call, every model invocation, every decision — for every agent run, in production, queryable after the fact.

This is one entry, not seven sub-protocols. The goal is the minimal complete picture: three signal types, one stack shape, what to instrument first.

---

## The Three Signals That Matter

### 1. Trace

A trace is a record of one agent run, end-to-end, as a tree of spans. Every tool call is a span. Every model invocation is a span. If you dispatch a subagent, that's a child trace under the parent.

**What a trace tells you:**
- Which steps happened, in what order
- How long each step took
- Where the run branched (and why)
- Which step failed (if any)
- The full input and output at each step

Without a trace, you know the final output was wrong. With a trace, you know which tool call produced the wrong intermediate result that caused the wrong final output. That's the difference between debugging for 3 hours and debugging for 10 minutes.

**The minimum trace record per span:**

```json
{
  "trace_id": "trc_abc123",
  "span_id": "spn_xyz789",
  "parent_span_id": "spn_parent",
  "agent_id": "summarizer-v2",
  "type": "tool_call",
  "name": "fetch_document",
  "started_at": "2026-04-30T14:22:01.000Z",
  "ended_at":   "2026-04-30T14:22:01.847Z",
  "input":  { "url": "https://..." },
  "output": { "content": "...", "status": 200 },
  "status": "ok"
}
```

The `trace_id` is the thread that connects every span in a single run. **Generate it at the entry point. Carry it through every downstream call, every subagent dispatch, every tool invocation.** If it breaks — if one span is missing a trace ID — you lose the ability to reconstruct that run.

### 2. Logs

Logs are the narrative layer. Traces tell you what happened; logs tell you why the agent made a specific decision at a specific point.

**Structured beats free-text, every time.** A log line like:

```
Agent decided to fetch document because query matched retrieval heuristic
```

loses to:

```json
{
  "trace_id": "trc_abc123",
  "span_id": "spn_current",
  "agent_id": "summarizer-v2",
  "level": "info",
  "event": "decision.fetch_triggered",
  "reason": "retrieval_heuristic_match",
  "confidence": 0.87,
  "ts": "2026-04-30T14:22:00.912Z"
}
```

The structured version is queryable. You can ask "show me all runs where `reason == retrieval_heuristic_match` and the final output was wrong" — and get an answer. Free-text logs don't support that query.

**What every log line must carry:**

| Field | Why |
|-------|-----|
| `trace_id` | Ties the log line to a specific run — the non-negotiable field |
| `span_id` | Ties the log line to a specific step within the run |
| `agent_id` | Which agent version emitted this — critical for multi-agent systems |
| `level` | `debug` / `info` / `warn` / `error` |
| `event` | A dot-namespaced event name: `decision.escalate`, `tool.retry`, `task.complete` |
| `ts` | ISO8601 timestamp |

Everything else is payload — add fields as needed for the decision context. Keep the schema stable; adding fields is fine, renaming or removing is a breaking change.

**Log at decision points, not at every line.** Decision points:
- The agent chooses between two possible next actions
- A tool call is retried
- The agent decides to escalate or complete
- An unexpected input is handled

### 3. Metrics

Metrics are the aggregate view over time. Traces and logs tell you about one run; metrics tell you whether 10,000 runs this week look better or worse than last week.

**The metrics that matter for agents:**

| Metric | What it tells you |
|--------|-------------------|
| `task.completion_rate` | What fraction of started tasks reach a successful terminal state |
| `task.latency_p50` / `task.latency_p99` | How long tasks take at median and at the tail |
| `tool.error_rate` by tool name | Which tools are failing and how often |
| `model.cost_per_task` | Token spend per completed task — catches prompt changes that blow up token usage |
| `model.cache_hit_rate` | For caching-enabled models: are you getting cache hits? |
| `agent.loop_depth` | How deep the agent loops before completing or failing — catches runaway loops |

**Metric shape:** counter, gauge, or histogram. Don't overcomplicate. A counter for `task.completed` and `task.failed`, a histogram for `task.latency_ms`, and a gauge for `tool.error_rate` covers most of what you need to start.

**Metrics without traces are insufficient for debugging** — you know something went wrong but can't look up the specific run. Traces without metrics are insufficient for capacity planning and trend detection — you can debug one run but can't see the pattern across thousands. You need both.

---

## A Minimal Stack That Works

Don't reach for a vendor until you know what you need. The shape of the stack matters more than the brand.

**The minimum viable observability stack:**

```
Agent process
  │
  ├── Emit trace spans → Trace backend (OpenTelemetry-compatible)
  │     OTLP export, batch send, async — don't block the agent on trace writes
  │
  ├── Emit structured logs → Log aggregator
  │     stdout as JSON lines (docker/k8s picks them up automatically)
  │     or direct to log aggregator via structured handler
  │
  └── Emit metrics → Metric backend
        Prometheus exposition format or OTLP metrics
        Increment counters at task start/end, record histograms at task complete
```

**OpenTelemetry is the right abstraction layer.** It's vendor-neutral, well-supported, and gives you structured spans with parent/child relationships for free. The overhead is minimal. Use it even if you don't know which backend you'll use — you can route OTLP to any backend later.

**Starter stack by deployment size:**

| Scale | Trace | Logs | Metrics |
|-------|-------|------|---------|
| 1 developer | File-based OTLP export | stdout JSON | Prometheus on localhost |
| Small team | Jaeger (self-hosted, free) | Loki or cloud logs | Prometheus + Grafana |
| Production | Honeycomb / Lightstep / Datadog | Same backend or cloud logs | Datadog / Grafana Cloud |
| Budget-first | Signoz (open-source, all three) | Signoz | Signoz |

The columns are independent — you can mix. The important thing is that all three columns share a `trace_id` field so you can cross-reference.

---

## What to Do First

80% of production debugging uses two signals: trace IDs and structured logs. Start there.

**Step 1: Generate a trace ID at every entry point.**

```python
import uuid

def handle_task(input: dict):
    trace_id = f"trc_{uuid.uuid4().hex[:12]}"
    context = {"trace_id": trace_id, "agent_id": "my-agent-v2"}
    # pass context to every downstream call
    result = run_agent(input, context=context)
    log({"event": "task.complete", **context, "status": "ok"})
    return result
```

If you do nothing else today, do this. Every log line now has a trace ID. When a user reports a problem, you ask them for the task ID (or timestamp), find the trace ID, and pull every log line for that run.

**Step 2: Emit structured log lines at decision points.**

```python
def log(data: dict):
    import json, sys
    print(json.dumps(data), file=sys.stdout, flush=True)
```

That's it. Stdout JSON, flushed immediately. Docker and Kubernetes capture it. Your log aggregator (Loki, CloudWatch, Datadog Logs) ingests it.

**Step 3: Add tool-call spans.**

Wrap every tool call with a span record — start time, end time, input, output, status. Write it to a file or OTLP endpoint. This is the trace. With step 1 (trace ID), step 2 (decision logs), and step 3 (tool call spans), you can reconstruct any agent run end-to-end.

**Step 4: Add the five key metrics.** (Do this after steps 1-3 are stable.)

Completion rate, latency histogram, tool error rate by tool, cost per task, cache hit rate. These are the metrics that will tell you whether a prompt change made things better or worse at scale.

---

## Instrumenting Subagent Dispatches

Multi-agent systems are harder to observe because a single user-visible task may fan out to 3-10 subagent invocations. The trace ID is what holds this together.

**The rule:** when the orchestrator dispatches a subagent, it passes the current `trace_id` and its own `span_id` as the `parent_span_id` of the subagent's first span.

```python
def dispatch_subagent(agent_name: str, input: dict, context: dict):
    child_context = {
        "trace_id": context["trace_id"],         # same trace ID
        "parent_span_id": context["span_id"],    # orchestrator's span is the parent
        "agent_id": agent_name,
    }
    return call_subagent(agent_name, input, context=child_context)
```

This creates a tree structure in your trace backend: the orchestrator span is the root, each subagent dispatch is a child span. You can see the full fan-out, which subagent took the most time, which one failed.

Without this, subagent runs appear as unconnected traces with no relationship to the task that triggered them.

---

## Common Anti-Patterns

**printf debugging in production**
Adding `print(f"DEBUG: tool called with {input}")` to understand a production failure. This gives you unstructured text with no trace ID, no agent identity, and no queryability. You can't search it. You can't aggregate it. You can't filter it by run. Fix: structured logs with trace ID from day one.

**"We'll add metrics later"**
You ship, you have traces and logs, metrics are on the backlog. A month later you have a performance regression and no historical baseline to compare against. Metrics are cheapest to add before you have data to analyze — adding them after means you have no history. Fix: add the five key metrics at the same time you add structured logging.

**Metrics without traces**
Your dashboards show that task completion rate dropped 8% on Tuesday. But you have no traces, so you can't look at the specific failed runs to understand why. You're left guessing. Fix: always pair metric anomalies with trace investigation. Without traces, metrics tell you something is wrong but not what.

**Logging everything at DEBUG level**
You log every intermediate value, every branch condition, every variable assignment. Ingestion cost explodes. Signal is buried in noise. Queries time out. Fix: log at decision points (the moments where the agent chose between meaningful alternatives), not at every step.

**Dropping trace ID in async boundaries**
The orchestrator has a trace ID. It dispatches an async task to a queue. The worker picks it up and starts fresh — no trace ID, no parent span. The trace is broken. Fix: serialize the trace context (trace ID, parent span ID) into the queue message payload; deserialize it in the worker before doing anything else.

**Observing only the happy path**
Your dashboards show metrics for completed tasks. Failed tasks, timeouts, and escalations are not instrumented. Fix: emit events for every terminal state — complete, fail, timeout, escalate, loop-limit-exceeded. The failure modes are where the signal is.

---

*Related: `@content/web/github/2026-11-23-claude-code-v2-1-331` · `@content/youtube/cole-medin/my-ai-software-factory-ships-hundreds-of-prs-a-week-heres-how-i-manage-it` · `@content/youtube/langchain/how-madrigal-pharmaceuticals-cut-time-to-production-from-12-weeks-to-2-with-langchain-langsmith` · `@content/youtube/langchain/introducing-langsmith-tuned-evaluators` · `@content/youtube/indy-dev-dan/claude-code-multi-agent-orchestration-with-opus-4-6-tmux-and-agent-sandboxes`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*