Skip to main content

08. Programming & Technologies

Logging, Tracing and Observability

Observability for Agentic AI means structured logs, distributed traces (spans for LLM turns, tools, retrieval, handoffs), and metrics for latency, tokens, cost, and errors β€” with redaction so prompts and secrets do not leak. You cannot debug multi-step agents from stdout vibes; you need request_id-correlated timelines and eval hooks fed by those traces.

What you will learn

  • Distinguish logs, traces, metrics, and eval signals
  • Design a span tree for a multi-tool agent run
  • List safe fields to log vs fields to redact
  • Define SLOs and alerts for agent cost and failures
  • Answer interview questions with short, solid answers
Logs traces metrics and evals for agents
Interview staple: traces show the path; metrics show the tax; logs explain the failure.

Definition

Logging records discrete events (JSON lines with severity and fields). Tracing records a causal timeline of spans inside one agent run (and across services). Metrics aggregate counters and histograms (requests, tokens, cost, latency, error rate). For agents, observability also feeds evals β€” sampling traces into quality scoring.

SDKs (OpenAI Agents tracing, LangSmith, OpenTelemetry, cloud APM) differ in UI; the mental model is the same: correlate everything with a request/run id.

Introduction

This lesson (#10 in Programming & Technologies) closes Module 08 after Docker/Kubernetes. Containers emit nothing useful unless you instrument them.

Next module: Advanced Concepts β€” starting with RAG and Agentic RAG.

Why agents need more than logs

  • Multi-step runs hide failures inside β€œ200 OK” HTTP responses
  • Cost is a first-class signal β€” tokens and tool calls
  • Retries and handoffs need a timeline, not scattered print statements
  • RAG bugs show up as wrong retrieved ids β€” must be recorded
  • Production incidents need tenant-scoped forensics without dumping PII

Structured logging

  • JSON logs: timestamp, level, message, request_id, tenant_id
  • Log tool name, status, latency_ms, error_class β€” not raw secrets
  • Use correlation ids from the edge through workers
  • Prefer semantic conventions over free-text essays
  • Sample or truncate bulky fields under policy
  • Ship to a central store (CloudWatch, Stackdriver, ELK, etc.)

Tracing agent runs

One user request should produce one root trace with nested spans.

Agent run trace with retrieve llm and tool spans
Frameworks often emit generation/tool/handoff/guardrail spans β€” keep your business spans too.
  • Root span: agent_run / workflow name
  • Child spans: retrieve, llm_turn, tool_call, handoff, guardrail
  • Attributes: model id, token counts, tool args hash, retryable flag
  • Propagate context across HTTP and queue workers
  • OpenTelemetry as a vendor-neutral backbone when possible
  • Link traces to stored run rows in SQL for audit

Metrics that matter

  • Request rate, success/error rate, p50/p95 latency
  • Tokens in/out and estimated cost per tenant
  • Tool error rate and top failing tools
  • Retrieval hit proxies (empty results, low score rates)
  • Queue depth / in-flight runs for workers
  • Budget exhaustion and rate-limit (429) counts

Privacy and redaction

Observability must not become a second data breach.

Safe log fields versus redacted sensitive fields
Default: log metadata and hashes; store full prompts only in gated debug modes.
  • Never log API keys, passwords, raw cards, or secrets
  • Gate full prompt/completion capture behind role + retention limits
  • Hash or truncate tool payloads that may contain PII
  • Honor tenant data residency for log/trace backends
  • Document retention: hot traces vs long-term audit summaries

From traces to evals and alerts

  • Sample production traces into offline eval sets
  • Score groundedness / tool success, not only uptime
  • Alert on error spikes, cost anomalies, and latency SLOs
  • Page on hard failures; ticket on quality regressions
  • Include model version and prompt version in every trace

Map to earlier modules

  • Agents SDK / LangSmith-style tracing = Module 07 practice
  • Docker/K8s pods must export logs/metrics/traces
  • HTTP status classification feeds error_class attributes
  • RAG retrieval ids belong on retrieve spans
  • Cloud APM products implement these ideas per vendor

Failure modes

  • Printf debugging only β€” no correlation ids
  • Logging full prompts with secrets to a shared channel
  • Traces without token/cost attributes β€” blind to spend
  • Metrics on HTTP 200 while tools failed inside the run
  • No sampling strategy β€” either empty or unaffordable volume

Program / implementation notes

Add a request_id middleware, structured JSON logging, and a root trace around Runner/kickoff with child spans for retrieve/LLM/tool. Export to your APM; add dashboards for tokens, cost, and tool errors before the next feature ships.

  • Prefer OpenTelemetry + your backend, or the framework’s native tracer
  • Next: RAG and Agentic RAG β€” Module 09

Advantages and limitations

  • Advantage: debug multi-step agents with a real timeline
  • Advantage: cost and quality become visible and alertable
  • Advantage: traces feed continuous eval loops
  • Limitation: naive full-prompt logging creates privacy risk
  • Limitation: high cardinality labels can explode metric bills
  • Limitation: tooling UIs differ β€” standardize on field names

Key points

  • Logs = events; traces = timelines; metrics = aggregates; evals = quality.
  • One agent run β†’ one trace with nested LLM/tool/retrieve spans.
  • Always record tokens, latency, model id, and outcomes.
  • Redact secrets and gate full prompt storage.
  • Alert on errors, latency SLOs, and cost anomalies.
  • Correlate with request_id / tenant_id across pods and queues.

FAQs

Logs vs traces?

Logs are discrete events. Traces connect timed spans into a parent/child timeline for one run β€” essential for multi-tool agents.

Do I need OpenTelemetry?

It is a strong default for portability. Framework-native tracing is fine if it exports the same fields you need for cost and tools.

Should we log every prompt in production?

Only under clear policy: access control, retention, and redaction. Prefer metadata always; full text for sampled debug or regulated audit stores.

What is a good first dashboard?

Requests, error rate, p95 latency, tokens/cost per tenant, and tool failure rate β€” with links from a failing request to its trace.

Interview questions

  1. What observability signals do agents need?

    Answer Structured logs, distributed traces of LLM/tool/retrieve steps, and metrics for latency, tokens, cost, and errors β€” plus eval sampling from those traces.

  2. What belongs on an LLM span?

    Answer Model id, input/output token counts, latency, finish/error status, and a correlation to the parent agent_run β€” not raw secrets.

  3. How do you debug a wrong agent answer?

    Answer Open the run’s trace: inspect retrieved chunk ids, tool args/results, and model turns in order β€” then fix retrieval, tools, or prompts with evidence.

  4. How do you keep observability safe?

    Answer Redact credentials and sensitive payloads, gate full prompt capture, enforce retention, and scope access by role and tenant.

  5. Which metrics catch runaway agents?

    Answer Token/cost per run and per tenant, step counts, 429s, timeout rates, and alerts when spend or latency exceeds budgets.

  6. How does this close Module 08?

    Answer Languages, providers, APIs, data, cloud, and containers only become operable when every agent run is logged, traced, and metered in production.

Related topics

Practice task

Complete each numbered practice step in a notebook or doc before opening the next lesson.

  1. Draw a span tree for: retrieve β†’ llm β†’ tool(create_ticket) β†’ llm final.
  2. List 8 fields on every log line and 5 fields you will never log.
  3. Define 3 alerts (error rate, p95 latency, daily token cost).
  4. Write a redaction policy for prompts in staging vs production.
  5. Answer interview questions 1, 2, and 4 in two sentences each.