Back to blog
November 25, 2026•50 views

AI Agent Observability: Logging, Tracing, and Debugging Multi-Step Agents in Production

ai agent observabilityai agent tracingdebug ai agentsllm tracingopentelemetryai automationmcp servers
AI Agent Observability: Logging, Tracing, and Debugging Multi-Step Agents in Production

Most agents work fine in a notebook and fall apart the moment a real user hits them. Not because the model is bad, but because nobody can see what happened. A request comes in, the agent calls three tools, retries one, hands off to a sub-agent, and returns something wrong. You open your logs and find a single line: "Agent completed in 12.4s." That line tells you nothing.

I have shipped agent systems for clients in Dhaka, Sydney, Austin, and Toronto, and the pattern is identical every time: the teams that debug fast are the ones that invested early in AI agent observability logging. Not dashboards. Not fancy evals. Just structured, correlated logs and traces that let you reconstruct any run, step by step, weeks after it happened.

This guide is the version of that setup I wish I had on my first agent project. It covers what to log per step, how to wire up AI agent tracing with OpenTelemetry, how to debug multi-step agent failures, and how to keep log volume and PII under control. If you are still deciding how to instrument the rest of your stack, the Next.js OpenTelemetry monitoring guide is a good companion read.

Why agent observability is harder than normal app monitoring

A conventional web app fails loudly. A 500 is a 500. An agent fails quietly. It returns a plausible sentence that is wrong, or it silently drops a tool call, or it loops four times on the same retry and burns $3 of tokens before giving up.

Three things make agents different from normal services:

  • Nondeterminism. The same input can produce different tool call sequences. You cannot reproduce a bug by replaying the request unless you also replay the model's decisions.
  • Deep call chains. One user message fans out into an LLM call, a tool call, a database query, another LLM call, and a sub-agent handoff. That is six or more spans for one logical action.
  • Payloads are huge and sensitive. Prompts and completions are kilobytes of text, sometimes containing customer data. You cannot dump them raw into CloudWatch and sleep well.

So the goal is not "more logs." The goal is a trace tree you can walk, plus a small number of high-signal log events attached to it.

The one artifact that changes everything: an agent event schema

Before you touch a logging library, define the shape of an agent event. This is the single highest-leverage decision in the whole project. If every step emits the same fields, your dashboards, alerts, and debugging queries write themselves.

Here is the schema I use. It has survived contact with production across several client systems.

Field Type Why it matters
trace_id string Ties every span in one user request together
span_id string Unique ID for this step
parent_span_id string Rebuilds the tree, essential for sub-agents and async tools
session_id string Groups multiple turns in one conversation
agent_name string Which agent or sub-agent emitted the event
step_index int Ordering within the run, even when timestamps collide
event_type enum llm_call, tool_call, handoff, retry, error, final
model string Model and version, so you can compare after a swap
input_tokens / output_tokens int Cost attribution and context-window pressure
latency_ms int Per-step timing, not just end-to-end
tool_name / tool_status string Which tool, and did it succeed
retry_count int Loops and flaky tools show up here first
decision_rationale string (truncated) The agent's stated reason for the next action
error_code string Stable codes, not free-text messages
redaction_applied bool Compliance audit trail

Two fields do most of the work: parent_span_id and step_index. The first lets you reconstruct the tree; the second lets you order events even when your log pipeline delivers them out of order (it will).

What to log per step

For an LLM step, log the model, token counts, latency, finish reason, and a truncated rationale. Do not log the full prompt at this level by default.

For a tool call, log the tool name, a hash or redacted summary of the arguments, the status, and the latency. If the tool hit an external API, log that API's request ID so you can cross-reference.

For a handoff, log from_agent, to_agent, and the reason. Handoffs are where multi-step agent debugging gets nasty, because context quietly gets dropped between agents and the receiving agent has no idea.

For a retry, log the attempt number and the error code that triggered it. A retry with no logged reason is a bug in your observability, not just your agent.

Wiring up AI agent tracing with OpenTelemetry

You do not need a vendor SDK to get started. OpenTelemetry gives you vendor-neutral traces, and most agent observability tools ingest OTLP directly. Here is a minimal but real instrumentation pattern in Python.

from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer("agent.runtime")

def run_step(agent_name, step_index, fn, **attrs):
    with tracer.start_as_current_span(f"agent.step.{step_index}") as span:
        span.set_attribute("agent.name", agent_name)
        span.set_attribute("agent.step_index", step_index)
        for k, v in attrs.items():
            span.set_attribute(f"agent.{k}", v)
        try:
            result = fn()
            return result
        except Exception as exc:
            span.set_status(Status(StatusCode.ERROR, str(exc)))
            span.record_exception(exc)
            span.set_attribute("agent.error_code", type(exc).__name__)
            raise

Wrap every LLM call, tool call, and handoff in its own span. The context manager handles parent/child relationships automatically as long as you pass the trace context through your async tasks. That last part is where most teams break it: if you fire a tool call into a background worker and do not propagate the context, you get an orphan span with no parent. Use your framework's context propagation (or manually pass traceparent headers per the W3C Trace Context spec) and verify the tree looks right in your UI before you trust it. The same discipline applies to the streaming tool calls in a location-aware AI chatbot built with the Vercel AI SDK, where each streamed tool call should land as its own span.

For Node/TypeScript services, the same idea with @opentelemetry/api:

import { trace, SpanStatusCode } from "@opentelemetry/api";

const tracer = trace.getTracer("agent.runtime");

export async function tracedStep<T>(
  agentName: string,
  stepIndex: number,
  fn: () => Promise<T>,
  attrs: Record<string, string | number> = {}
): Promise<T> {
  return tracer.startActiveSpan(`agent.step.${stepIndex}`, async (span) => {
    span.setAttribute("agent.name", agentName);
    span.setAttribute("agent.step_index", stepIndex);
    for (const [k, v] of Object.entries(attrs)) span.setAttribute(`agent.${k}`, v);
    try {
      return await fn();
    } catch (err) {
      span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
      span.recordException(err as Error);
      throw err;
    } finally {
      span.end();
    }
  });
}

The pattern is the same whether you are building on Claude, GPT, or a local model. The model is a detail; the trace structure is the product.

Debugging multi-step agents: a repeatable workflow

When a client reports "the agent gave a wrong answer," I do not read the final output first. I walk the trace. Here is the order that finds the root cause fastest.

  1. Find the trace by session or user turn. Pull the trace_id from the request log, not the agent log.
  2. Render the span tree. Look for missing parents, orphaned tool calls, and unusually deep nesting. A depth of 15 on a simple query usually means a loop.
  3. Check step ordering against step_index. If steps are out of order, you have an async bug before you even look at content.
  4. Inspect retries and error codes. A burst of retry_count > 0 on one tool tells you the tool is flaky, not the model.
  5. Read the decision rationale at the failing step. This is where the agent "explains" itself. It is often wrong, but it is always informative.
  6. Compare token counts across steps. A step that suddenly consumes 40k input tokens usually has a context-stuffing bug.
  7. Only then open the redacted prompt/completion for that single step, with PII scrubbed.

That workflow takes minutes instead of hours. The difference between a team that debugs in five minutes and one that debugs for a day is almost never model choice. It is whether step 2 is possible at all. If your agents call MCP tools, the same tree walk applies, the MCP server security patterns guide covers the auth and rate-limit attributes worth attaching to those spans.

Agent observability tools: what actually matters

There are a lot of options now, and the honest answer is that most teams should start with OpenTelemetry plus a cheap backend, then graduate to a specialized platform when volume justifies it. Here is how the main categories compare.

Approach Strengths Weaknesses Good fit
OpenTelemetry + generic backend (Grafana, Jaeger, Datadog) Vendor-neutral, cheap at scale, one stack for app + agents No LLM-aware UI, you build the tree view yourself Teams already on OTel, cost-sensitive projects
LLM observability platforms (LangSmith, Langfuse, Arize Phoenix) Prompt/completion views, evals, dataset replay out of the box Per-seat or per-trace pricing, another vendor Teams shipping agents weekly who need eval loops
Framework-native tracing (built into agent frameworks) Zero setup, instant visibility Tied to the framework, weak correlation with your app logs Prototypes and early pilots
DIY structured logs to Postgres/S3 Full control, data residency, cheapest storage You own the UI, retention, and every query Regulated clients, low-bandwidth or data-residency constraints

For a lot of the work I do with founders in Bangladesh and Australia, the last row wins on cost and compliance. Shipping gigabytes of traces to a US SaaS from a Dhaka data center is both slow and, for some clients, a legal headache. A local Postgres with partitioned trace tables plus a small Grafana instance goes a long way.

Cost, volume, and PII: the parts nobody warns you about

Agent logs grow faster than any logs you have shipped before, because every step carries text. Two controls keep this sane.

Sampling

Do not sample uniformly. Sample by outcome and by risk:

  • Keep 100% of traces that contain an error, a retry, or a handoff.
  • Sample 10 to 20% of successful traces for general analytics.
  • Keep 100% of traces for a small set of flagged users or tenants.

This gives you full fidelity where bugs live and cheap coverage everywhere else.

Redaction and retention

Run a redaction pass before anything leaves the process. Strip emails, phone numbers, card patterns, and anything your client's compliance team flags. Store the redaction decision (redaction_applied) so an auditor can verify it later. For retention, most clients are comfortable with 30 days of full traces and 12 months of aggregated metrics. Keep the raw prompts shorter than the traces.

If you are in a low-bandwidth environment, ship spans in batches with a local buffer and never block the agent on log delivery. A dropped trace is annoying; a stalled agent because the log endpoint timed out is a production incident. If you are handing this system to a client or a new hire, the NIST cybersecurity guide for solopreneurs is a useful checklist for the logging and data-handling expectations they should demand.

A copy-paste logging checklist

Before you call an agent "production ready," confirm these:

  • Every step emits the full event schema, including parent_span_id and step_index
  • Trace context propagates through async tasks and background workers
  • Retries log the triggering error code
  • Handoffs log from_agent, to_agent, and reason
  • Token counts are recorded per step, not just per run
  • PII redaction runs before shipping, with an audit flag
  • Sampling keeps 100% of errors and retries
  • Retention policy is documented and enforced
  • A single query can pull a full trace tree by session_id

If any box is unchecked, you do not have observability. You have logs.

Where to go from here

Agent observability is not a nice-to-have you bolt on after launch. It is the difference between shipping confidently and shipping and praying. If you take one thing from this post, make it the event schema. Define it, enforce it, and the tracing, dashboards, and debugging workflow fall into place around it.

If you are building a multi-step agent and want a second set of eyes on the logging and tracing setup before it hits production, that is the kind of work I do most weeks. I help founders and engineering teams in Bangladesh, Australia, the USA, Canada, and New Zealand get their Next.js apps and AI automation systems instrumented properly. Reach out through the site and tell me what your agent does; I will tell you what to log first.

Frequently asked questions

Do I need a paid observability platform to debug agents?

No. OpenTelemetry plus a generic backend such as Grafana, Jaeger, or partitioned Postgres tables covers most of what you need. Specialized LLM observability platforms earn their cost when you need prompt/completion views, eval loops, and dataset replay at volume.

What is the single most important field to log for multi-step agents?

parent_span_id, followed by step_index. The parent lets you rebuild the trace tree, and a stable step index lets you order events correctly even when your log pipeline delivers them out of order.

How should I handle PII in agent logs?

Redact in-process before anything leaves the service. Strip emails, phone numbers, and card patterns, record a redaction_applied flag for audits, and keep raw prompt retention shorter than aggregated metrics retention.

Can I trace agents built on MCP servers the same way?

Yes. Treat each MCP tool call as a span with the server name and tool name as attributes, and propagate traceparent through the MCP request so the call stays attached to the parent agent step.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp