Skip to content
bits
Ship an agent to the edge · Lesson 6 of 8

Logs you can query

Tutor:

When a user says “the agent gave me nonsense at lunchtime”, you need to find that run among thousands. That only works if you logged it in a shape you can search.

Turn on Workers Logs and traces in the config. Everything your Worker writes with console.log is then kept and searchable in the dashboard:

{
"observability": {
"enabled": true,
"head_sampling_rate": 1,
"traces": { "enabled": true }
}
}
JSONUTF-8
Tutor:

head_sampling_rate is the share of requests to keep, from 0 to 1. Keep all of them while traffic is small and lower it later. Traces need their own enabled flag; the top-level one alone only turns on logs.

Tutor:

Now the important part: log objects, not sentences. Workers Logs indexes the fields of a JSON object, so you can filter on any of them.

A sentence vs An objectcompare
A sentence

turn 2 for user 8f3a done (end_turn), 1834 in / 212 out

An object

{ event: "turn", user: "8f3a", turn: 2, stop_reason: "end_turn", input_tokens: 1834, output_tokens: 212, ms: 2310 }

Tutor:

To find every run where stop_reason was max_tokens, the sentence needs a text search and luck. The object needs one filter. Log one line per model call, inside the loop:

const started = Date.now();
const res = await client.messages.create({ model, max_tokens: 4096, tools, messages });
console.log(JSON.stringify({
event: "turn",
user: userId,
turn,
model: res.model,
stop_reason: res.stop_reason,
input_tokens: res.usage.input_tokens,
output_tokens: res.usage.output_tokens,
ms: Date.now() - started,
}));
TypeScriptUTF-8● lines 3–12: one line per turn
Tutor:

What's not in it matters as much. No prompt text, no tool results, no email addresses, no keys. Logs are copied around, kept for days and read by people who don't need your users' words. Log an opaque user id, the shape of the run and the numbers. If you need the actual prompts for debugging, AI Gateway already keeps them, under its own retention settings.

For failures, use console.error. Workers groups errors and exceptions into Workers Issues, so a new kind of failure shows up once, with a count, instead of as a thousand loose lines.

While you're developing, stream the deployed Worker's logs live. --search keeps only lines that contain the text:

OUTPUT
npx wrangler tail --search "turn"
# example output, trimmed to your log lines
{"event":"turn","user":"8f3a","turn":1,"stop_reason":"tool_use","input_tokens":1610,"output_tokens":64,"ms":1290}
{"event":"turn","user":"8f3a","turn":2,"stop_reason":"end_turn","input_tokens":1834,"output_tokens":212,"ms":2310}
quick check+20 neurons
Tutor:

Which log line lets you filter the dashboard for runs that hit max_tokens?

    Type your answer or tap an option · Enter checks

    quick check+20 neurons
    Tutor:

    Which of these belongs in your per-turn log line?

      Type your answer or tap an option · Enter checks