AI Agent Logging Best Practices 2026
The hardest question when an agent misbehaves is what it was thinking. Plain logs record events; an agent needs the whole execution tree: input, steps, tool calls, the reason for the answer, and the token cost. Here is a field design and code you can copy.
📜 Table of Contents
📖 Keep reading
Logging for AI Agents: Record the Reasoning
When an agent gets something wrong, the hard question is what it was thinking. Normal logs record isolated events; an agent request is a tree — one input, several model calls, a handful of tool calls, one answer. With the right fields, debugging becomes reading instead of guessing.
Why plain logs fail
Line-oriented logs scatter the pieces. Give every request a trace_id and every step a sequence number, and the chain reassembles in order.
Field design
| Field | Type | Purpose |
|---|---|---|
| trace_id | string | One per request, carried through every step |
| session_id | string | Conversation, for multi-turn context |
| step | int | Ordering, from 1 |
| event | string | request_start / llm_call / tool_call / output / error |
| model | string | Model and version |
| prompt_version | string | Pinpoints which edit caused a regression |
| tool / tool_args | string / object | Name and arguments, redacted |
| latency_ms | int | Step duration |
| input_tokens / output_tokens | int | Step cost |
| error_code | string | Empty on success |
One full trace
JSON Lines, one event per line, ready for Loki, Elasticsearch or ClickHouse:
{"ts":"2026-11-25T10:30:00.123Z","trace_id":"a1b2c3d4","step":1,"event":"request_start","input_len":42}
{"ts":"2026-11-25T10:30:00.130Z","trace_id":"a1b2c3d4","step":2,"event":"llm_call","model":"gpt-4.1-mini","prompt_version":"v12","latency_ms":820,"input_tokens":1830,"output_tokens":96}
{"ts":"2026-11-25T10:30:01.010Z","trace_id":"a1b2c3d4","step":3,"event":"tool_call","tool":"get_weather","latency_ms":240,"ok":true}
{"ts":"2026-11-25T10:30:01.400Z","trace_id":"a1b2c3d4","step":4,"event":"output","latency_ms":390,"total_tokens":2054}
Four lines answer four questions: where it was slow, where it was expensive, what it called, which prompt it used.
Attaching trace_id automatically
import contextvars, logging, json, uuid
trace_id_var = contextvars.ContextVar("trace_id", default="-")
class TraceFilter(logging.Filter):
def filter(self, record):
record.trace_id = trace_id_var.get()
return True
handler = logging.StreamHandler()
handler.addFilter(TraceFilter())
log = logging.getLogger("agent")
log.addHandler(handler)
log.setLevel(logging.INFO)
def handle(user_input: str):
trace_id_var.set(uuid.uuid4().hex[:16])
log.info(json.dumps({"event": "request_start", "input_len": len(user_input)}))
contextvars propagate through asyncio tasks and FastAPI. Thread pools need an explicit copy_context(), otherwise workers inherit the default value.
What never goes in a log
| Content | Handling |
|---|---|
| API keys, tokens, passwords | Never; add a regex backstop in the log layer |
| Phone, ID, card numbers | Mask or hash |
| Full user conversation | Length and hash by default, fetch by trace_id when needed |
| Full system prompt | Version number only |
| Raw tool responses | Truncate to a fixed length |
Redact at the writer, not at each call site. One leak into central storage costs far more than prevention.
Sampling tiers
Keep the skeleton (trace_id, event, latency, tokens, error) for everything — it is tiny. Record full payloads for 5-10% of traffic, 100% of errors, and every request slower than p95.
Queries worth having
| Question | Query |
|---|---|
| Why was this answer wrong? | session_id → trace_id, replay the chain |
| Why did one error spike? | Group by error_code over time |
| Did the prompt change hurt? | Group by prompt_version, compare success rate and tokens |
| Where is the money going? | Sum output_tokens by model and caller |
Retention
Seven days hot, thirty days warm, archive for compliance. Estimate volume as QPS × bytes per request × 86400 before choosing a policy.
FAQ
Is logging full prompts too expensive? Yes — a 2000-token prompt is roughly 8KB, so 100k requests means 800MB. Log the version and length, sample the content.
Structured or plain text? Structured. Agent debugging is multi-dimensional filtering; grep does not scale to it.
How do I correlate services? Pass trace_id in a header (X-Trace-Id or W3C traceparent), and put it in queue message bodies.
OpenTelemetry or not? Worth it for multi-service traces with log↔trace jumps. Single-service projects are fine with JSON Lines.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.