Lesson 8.2: Tracing, logging and observability for agents
Learn how to see what an agent did: traces and spans, what to record, sampling that keeps rare failures, the cost of storage and protecting personal data.
By the end of this lesson you will be able to describe a trace and its spans, decide what an agent should record at each step, build a view that answers the questions an operator asks, sample traces so that storage stays affordable without losing the rare failures you most need, and protect personal data in what you keep. You will work out that keeping every trace of 20,000 runs a day at 150 KB each for 30 days needs 90 GB, that keeping every failed run and a tenth of the rest needs about 13 GB, and that a sample of 1 per cent would catch an issue hitting 0.2 per cent of runs on only 33 per cent of days. You should have read Lessons 7.1 and 7.4. No code is needed. The mathematics is multiplication and the chance of at least one event.
Lesson 7.4 told you to find the first wrong step in a trace. That presumes you have one. Many teams put an agent into use and discover, at the first odd result, that nothing was recorded, or that what was recorded is a pile of unreadable text. An agent cannot be run responsibly if you cannot see what it did. This lesson covers how to make an agent observable, meaning that from the outside you can answer questions about its behaviour, including questions you did not think of in advance.
Why agents need more than ordinary logs
An ordinary program does the same thing for the same input, and a log line or two usually tells you what went wrong. An agent is different in four ways.
Its path varies. The same request can take different routes on different days, so you cannot reason about what happened from the code alone. You need the record of what did happen.
Its decisions are in text. Why it called a tool is in the model's output and the context it saw. Without them the "why" is lost.
It spans many calls. One user request may produce twenty model calls, thirty tool calls and several sub-agents. A log of unconnected lines cannot be assembled into a story without a common thread.
It costs money by the step. To control cost you must see which steps spend it.
The tool for all of this is the trace.
Traces and spans
A trace is the complete record of one run, from the request arriving to the final result. It is built from spans. A span is one unit of work with a start and an end: a model call, a tool call, a retrieval, a check or a hand-off to a sub-agent. Spans nest. The whole run is the top span. Inside it are the model calls and tool calls, and inside a sub-agent's span are that agent's own calls.
Picture a run as a tree:
Run: "Refund order 5521" (8.4 s, Rs 3.70)
├── Model call: classify request (0.9 s, 410 tokens in, 12 out)
├── Tool call: findorder(5521) (0.6 s, ok)
├── Model call: decide next step (1.8 s)
├── Tool call: getpolicy("damaged goods") (0.4 s, ok)
├── Sub-agent: verify evidence (2.1 s)
│ ├── Model call: inspect photo description (1.2 s)
│ └── Tool call: fetchattachment (0.7 s, ok)
├── Tool call: proposerefund(5521, 2400) (0.5 s, waiting for approval)
└── Model call: write reply (1.5 s)
A trace like this answers many questions at a glance. Where did the time go? What did the agent decide at each step? Which tool failed? What did the sub-agent do? A flat list of log lines would need to be pieced together by hand.
Every span carries a trace ID, shared by the whole run, and a parent ID, naming the span that started it. These two fields let a tool assemble the tree. The trace ID should also appear in logs elsewhere, and in the tools' own records, so that you can follow a run into the systems it touched. When a customer says "your assistant did something odd at 3 p.m.", you should be able to find the trace from the customer's ID and the time, and from there the exact records changed.
What to record
For each span, a useful minimum is:
Field · WhyTrace ID, span ID, parent ID · To assemble the tree
Kind and name · Model call, tool call, retrieval, check, hand-off
Start time and duration · To find delay
Status · Success, error, timeout, cancelled
Inputs · For a model call, the prompt or a reference to it. For a tool, the arguments
Outputs · The model's reply and tool calls. The tool's result, perhaps trimmed
Model and settings · Which model and version, temperature and any settings
Tokens and cost · In, out, cached, and the cost computed from them
Error details · Message, type, retry count
And for the whole run:
Who and what. The user or customer ID (pseudonymised if possible), the channel, the version of the instructions and tools, and the agent's version.
The outcome. Success or failure as best you can tell, a user rating if there is one, and any human approval or edit.
Totals. Steps, tokens, cost, elapsed time.
Flags. Hit a step cap, hit a cost cap, escalated, repeated a call.
Record versions carefully. If you cannot tell which version of the prompt and tools produced a trace, you cannot say whether a change made things better or worse, nor reproduce a failure. Give the instructions, the tool definitions and the model setting each a version, and store those with the trace.
Recording the reasoning
The model's visible reasoning, the plan or explanation it writes before acting, is among the most useful things to keep, since it answers "why did it do that?". Store it with the span. Note that some models hide part of their internal reasoning and return a summary, and you can only record what is returned.
What not to record
Recording everything has costs, which later sections cover. Be thoughtful about three kinds of content.
Personal and sensitive data. Names, ID numbers, card numbers, health details and passwords. See the section on privacy below.
Secrets. API keys and tokens must never reach the trace. Redact them before storing.
Enormous payloads. A full document of 200 pages in every span is wasteful. Store a reference and a hash, with the document kept elsewhere, or store a trimmed excerpt.
The questions a trace should answer
Design what you record around the questions an operator asks. Four groups cover most needs.
Debugging a single run. What happened, in order? Where did it first go wrong? What did the model see at that step? Did a tool fail? Which version ran?
Understanding behaviour in aggregate. What are the most common paths? How many steps does a typical run take? Which tools fail most often? Which requests lead to escalation?
Controlling cost and speed. What does a run cost on average and at the 95th percentile? Which steps cost most? Where does the time go? Which users or tasks cost the most?
Detecting trouble. Is the failure rate rising? Is cost per run jumping? Are runs hitting caps more often? Is a new kind of error appearing? Did a change in the last release make things worse?
If the data you record cannot answer one of these, add the missing field.
Views and dashboards
Raw traces are for debugging a single run. For the aggregate questions, build a few simple views from the data.
A run list with filters by time, user, outcome, cost, flags and version, each row linking to its trace.
A trace viewer that shows the tree, with timings, and lets you open any span's input and output.
A health dashboard with the success rate, escalation rate, errors by tool, cost per run and runs hitting caps, over time, so that a change shows as a step in a line.
A cost view by step kind, model, tool and user.
A comparison view that sets two versions side by side on the same metrics.
You do not need to build all of this at once. Many teams start with a trace viewer and a daily table of cost and success, and add views as questions come up. There are tools, open and commercial, that provide tracing for model applications, and standards for how spans are named and carried. Using one saves time. Choose one that stores traces in a form you can export.
Sampling: you cannot keep everything
A trace is large. It holds prompts, results and reasoning for every span. Suppose a run produces 150 KB of trace, and you handle 20,000 runs a day. That is 3 GB a day. Keeping 30 days is 90 GB. Keeping a year is over a terabyte. The storage cost is moderate, but the cost of searching it, of protecting it and of the personal data it holds grows with it. So most teams keep less than everything.
The question is what to drop. Dropping at random loses the rare, important traces. Better is tail-based sampling, a rule that decides after the run, when you know how it went.
Keep every trace that failed, hit a cap, escalated, had a user complaint or a negative rating, or was unusually costly or slow. These are the ones you will want.
Keep a share of ordinary successes, such as 10 per cent, chosen at random, as a baseline for comparison.
Keep all traces for new versions for a while, such as the first week after a change, since that is when problems show.
Keep a short summary of every run, even if the full trace is dropped: the run's totals, outcome, versions and flags. This is small and keeps the aggregate views accurate.
Suppose 5 per cent of runs fall in the "keep always" group. Keeping those and 10 per cent of the other 95 per cent means keeping 5% + 0.95 × 10% = 5% + 9.5% = 14.5% of traces. Of 90 GB, that is about 13 GB, 14.5 per cent of the storage, with every important trace preserved.
Predict first: you handle 20,000 runs a day, 5 per cent are failures or other flagged runs, and you keep every flagged run plus 10 per cent of the rest. What share of traces do you keep, and how much storage do you need for 30 days at 150 KB a trace? Work it out before reading on.
You keep 14.5 per cent, which is 2,900 traces a day, and about 0.435 GB a day, so about 13 GB over 30 days.
The sample that misses the rare problem
A flat sample is cheap and misleading when you hunt for a rare issue. Suppose an issue appears in 0.2 per cent of runs. With 20,000 runs a day, that is 40 occurrences a day. If you keep a random 1 per cent of traces, the chance of keeping at least one of the 40 is 1 − 0.99⁴⁰ = 1 − 0.669 = 33 per cent. On two days out of three you see none. With a 5 per cent sample it is 1 − 0.95⁴⁰ = 87 per cent. With 10 per cent it is 98.5 per cent. With a full capture it is 100 per cent.
This is why sampling rules should favour the unusual. If you can recognise the issue as it happens, for example by a particular error, you can keep every such trace regardless. The cost is that you can only keep what you can recognise, which is why a baseline sample of ordinary runs and a periodic human review of random traces are worth keeping.
Privacy and security of traces
A trace holds the text of conversations and tool results. It can therefore hold exactly the personal and sensitive data you work hard to protect elsewhere. A store of traces is a new copy of that data, often with broader access than the original. Treat it as sensitive.
Minimise. Record what you need. Do not log full documents or payment details when a reference will serve.
Redact before storing. Run a pass that removes or masks card numbers, ID numbers, secrets and, where not needed, names and contact details. Do it before the data is written, as redacting later leaves a window.
Control access. Few people need to read raw traces. Give access by role, log who looked and keep customer data out of general dashboards.
Limit retention. Keep traces only as long as you need them, and delete automatically. Set a shorter life for traces with personal data, and keep only anonymised totals longer.
Honour deletion requests. If a person asks that their data be deleted, you must be able to find and remove their traces. That is easier if traces carry a pseudonymous user ID that you can look up.
Protect the store. Encrypt it, back it up and secure it like any database of sensitive data.
Remember what the law requires. Rules on personal data differ by country and sector, and an agent in a regulated business, such as lending, may have record-keeping duties too. Check with whoever handles compliance. Keeping an audit trail of decisions, and limiting personal data in traces, can pull in opposite directions, and the answer is a deliberate policy.
From traces to improvement
Observability pays off when it feeds improvement.
Weekly review. Read ten to twenty traces, a mix of failures, expensive runs and random ones. You will spot problems no dashboard shows.
Failures become tests. Every failure you understand becomes a task in the evaluation set from Lesson 7.1.
Find repeated paths. If 80 per cent of runs follow one path, consider turning it into a workflow, as Lesson 6.4 advised.
Track the effect of changes. Use version fields to compare success, cost and speed before and after.
Close the loop with users. Link a user's rating or complaint to its trace, so that you can see what went wrong in the cases they cared about.
Three worked examples
Example 1: finding the first wrong step
A customer is told an order is not eligible for a refund, and complains. Support enters the order number and finds the trace. It shows that in step 4 the policy lookup returned the policy for a different product category, since the tool matched on a keyword. The model reasoned correctly from the wrong policy. The error took five minutes to find. Without the trace, the team would have blamed the model and spent days adjusting the prompt. They fixed the lookup, added a test and found 14 other traces over the past month with the same fault, which the customer service team contacted.
Example 2: a cost spike
The health dashboard shows cost per run rising from ₹3.70 to ₹5.60 over three days. The cost view by step shows the increase is entirely in one step, the summariser. The version field shows a prompt change on day one that added a long instruction block to that step. Because the instruction block is sent on every call, it adds to every run. The team shortens the block and caches it, and cost returns to ₹3.80. Without versions and per-step cost, they would have looked at traffic and models first.
Example 3: sampling that hid a bug
A team kept a flat 2 per cent of traces. An error affecting 0.1 per cent of runs, 20 a day, went unnoticed for two weeks: the chance of keeping at least one in a day was 1 − 0.98²⁰ = 33 per cent, and the few kept traces looked like noise. A customer complaint led to a manual search, which found it. The team changed to tail-based sampling that kept every trace with a tool error, every escalated run and every run with a negative rating, plus a 5 per cent baseline. The next new error appeared in the "keep always" set within a day.
A checklist for observability
1. Give every run a trace ID and every span a parent ID. Carry the trace ID into the tools and other logs.
2. Record for each span: kind, timing, status, inputs, outputs, model and settings, tokens and cost, and errors.
3. Record for each run: user (pseudonymised), channel, versions, outcome, totals and flags.
4. Version the instructions, tools and agent and store the versions with each trace.
5. Write down the questions you need to answer and check the data can answer them.
6. Build a trace viewer, a run list and a daily health and cost view.
7. Use tail-based sampling: keep every flagged run, a baseline sample and a short summary of all.
8. Redact personal data and secrets before storing. Control access and set retention.
9. Review a handful of traces every week, and turn failures into tests.
Common mistakes
No trace, only scattered log lines. You cannot rebuild a run.
No versions. You cannot tell which change made things better or worse.
Not recording the reasoning or the inputs. You will see what happened and not why.
Recording secrets and personal data. The trace store becomes a leak.
A flat random sample. It drops the rare failures you need.
Keeping everything forever. Cost and exposure grow.
Dashboards with no traces behind them. You see that something is wrong and cannot find why.
Never reading traces. Dashboards miss the odd and the new.
Traces that cannot be deleted by person. You cannot honour a deletion request.
Key takeaways
A trace is the complete record of a run, built from nested spans for model calls, tool calls, retrievals, checks and sub-agents. Trace and parent IDs assemble the tree.
Record timing, status, inputs, outputs, model, tokens, cost and errors for each span, and versions, outcome, totals and flags for each run.
Design what you record around the questions you must answer: debug a run, understand behaviour, control cost and speed, and detect trouble.
Keeping every trace is costly: 90 GB for 30 days in the example. Tail-based sampling that keeps flagged runs and a tenth of the rest needs about 13 GB.
A flat 1 per cent sample would see an issue hitting 0.2 per cent of runs on only 33 per cent of days, so sampling should favour the unusual.
Traces hold sensitive data. Minimise, redact before storing, restrict access, limit retention and support deletion.
Read traces every week and turn failures into tests.
Check yourself
1. What is a span and how do spans form a trace?
A span is one unit of work, such as a model call or a tool call, with a start and an end. Spans nest by parent ID, and all share a trace ID, forming a tree for the run.
2. Why record the version of the prompt and tools with each trace?
Without it you cannot tell which version produced a result, so you cannot compare versions or reproduce a failure.
3. 50,000 runs a day, 200 KB per trace, 14 days kept. How much storage if every trace is kept?
50,000 × 200 KB = 10 GB a day. Over 14 days that is 140 GB.
4. An issue appears in 0.5 per cent of 10,000 daily runs, and you sample 2 per cent at random. What is the chance of keeping at least one trace of it in a day?
There are 50 occurrences. 1 − 0.98⁵⁰ = 1 − 0.364 = 0.636, about 63.6 per cent.
5. What is tail-based sampling?
Deciding which traces to keep after the run, when its outcome is known, so that failures, escalations and unusual runs are always kept and ordinary ones are sampled.
6. Name three ways to protect personal data in traces.
Any three of: record only what is needed, redact before storing, control access, set short retention, support deletion and secure the store.
Try this
Set aside seventy-five minutes.
1. Draw a trace tree for one run of an agent you know or imagine, with its spans and sub-agent.
2. List the fields you would record for each span and for the run. Mark anything personal or secret and how you would redact it.
3. Write ten questions an operator might ask. For each, say which fields answer it. Add any missing field.
4. Estimate runs a day and trace size. Use the storage simulator to compare keeping everything with tail-based sampling.
5. Decide which runs are "keep always". Use the second simulator to see whether your baseline sample is large enough to catch a rare issue.
6. Write a retention rule and an access rule for traces.
7. Plan a weekly trace review: who reads, how many and what happens to what they find.
A good result is an observability plan: the span design, fields, versions, views, sampling rules and privacy policy. Lesson 8.3 turns to agents whose runs last not seconds but hours or days, and so must survive interruption.
Tags: Agentic AI Observability Tracing Logging Agent operations