# Log what your AI agent does: an audit trail you can read

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-11-02
- Updated: 2026-11-03
- Canonical (HTML): https://wurk.fun/blog/log-what-your-ai-agent-does-an-audit-trail-you-can-read
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/3e4f3be0-21a9-4770-bb7b-509ed434d83a/cover-agentlog.jpg?wurkUpload=v1.tugzF5mez1O3KgBSQnAAqhbqG1xu_2O_a-0runLVhrA

---

Your agent pays per request for an API it uses on jobs, and this morning the same call shows up as paid twice. You can't tell whether it saw the job twice, misread a response, or retried on its own after a timeout. Every hour you spend guessing is an hour you're not earning, and nothing stops it happening again tonight.

The fix is an action log: one JSON line for every action your agent takes, written the moment the action finishes. Each line records what the agent saw, what it decided, what tool it called with which inputs, what came back, what it cost, and the reason the agent gave. Replay the run from the log and the double payment stops being a mystery. This article gives you the format, the redaction rules, a small Python helper, and the one-line queries that answer "what did it spend today".

## The three questions a log must answer

When something goes wrong, you need three answers, in this order:

1. **What did it see?** The job listing, the task text, the API response. If the agent acted on bad input, the log has to show the input.
2. **What did it decide?** Which action it picked, and the reason it gave. This separates a logic bug from a prompt problem from a bad upstream response.
3. **What did it do?** The exact tool call, its inputs, and the result or status.

If your log can't answer all three without re-running the agent, it's decoration, not an audit trail. Every field in the next section exists to answer one of these questions.

## What to log, per action

The format is [JSON Lines](https://jsonlines.org/): one JSON object per line, plain text, easy to grep. One line per completed action:

```json
{"ts":"2026-11-02T06:41:02.318Z","run_id":"a1b2c3","step":4,"tool":"paid_fetch","inputs":{"url":"https://api.example.com/v1/translate","max_usdc":0.05},"status":"timeout","result":"no response in 30 s","cost":null,"reason":"Translate the caption for job 7"}
{"ts":"2026-11-02T06:41:33.901Z","run_id":"a1b2c3","step":5,"tool":"paid_fetch","inputs":{"url":"https://api.example.com/v1/translate","max_usdc":0.05},"status":"ok","result":"200, 412 chars of text","cost":0.05,"reason":"Retry after timeout"}
```

Fields worth locking in: the timestamp is UTC in ISO 8601, with milliseconds, so lines sort correctly no matter where you read them. The run id groups every action of one job. The step number gives the order inside that job. Status is ok, error, or timeout, never blank. The result is a short summary of what came back, which is your record of what the agent saw. Cost is per action, in whatever unit you actually pay with, and empty when you don't know yet. The reason is the agent's own stated justification, kept short.

Read those two lines together and the mystery is gone. Step 4 timed out, step 5 retried, and "Retry after timeout" tells you the second payment came from a retry loop, not a duplicate job. A timeout doesn't prove the first payment failed, so the fix is in the retry logic, not the job board. ([Idempotency keys](https://wurk.fun/blog/idempotency-keys-stop-your-ai-agent-from-paying-twice) are the usual cure.)

## What never goes in the log

API keys, private keys, wallet seed phrases, session tokens, bearer tokens, passwords. Never. Not obfuscated, not "just for debugging": a log you can read is a log anyone with file access can read, and rotation and backups spread it further.

Redact before the line is written, not after. Matching credential-looking field names and replacing their values is the minimum. The [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) lists access tokens, passwords, encryption keys and payment card data among the things that should not be recorded directly, and says stored logs must be protected from tampering and unauthorized access. Also truncate long strings. A full 40-line prompt echoed into every action line makes the log unreadable and slow to search.

Rule of thumb: if a value would let someone act as you, spend your money, or recover your wallet, it gets replaced with a marker before it ever reaches disk.

## A small Python helper

```python
import json, re, datetime

LOG = "agent_actions.jsonl"
SECRET = re.compile(r"(?i)key|token|secret|password|seed|authorization|credential")

def redact(v):
    if isinstance(v, dict):
        return {k: ("***REDACTED***" if SECRET.search(k) else redact(x)) for k, x in v.items()}
    if isinstance(v, list):
        return [redact(x) for x in v]
    if isinstance(v, str) and len(v) > 300:
        return v[:200] + "...TRUNCATED"
    return v

def log_action(run_id, step, tool, inputs, status, result="", cost=None, reason=""):
    line = {"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
            "run_id": run_id, "step": step, "tool": tool, "inputs": redact(inputs),
            "status": status, "result": str(result)[:200], "cost": cost, "reason": reason[:200]}
    with open(LOG, "a") as f:
        f.write(json.dumps(line, separators=(",", ":")) + "\n")
```

Drop `log_action` into your agent's action loop, one call per completed action. The helper only ever appends, so the agent's own code never rewrites history. That's not tamper-proof (anyone with access to the file can still edit it), so keep the log where the agent's tools can't reach it. The name pattern also catches harmless fields like "keyword"; over-redacting is the safe direction to be wrong. For rotation, point logrotate at the file, or include the UTC date in the filename so each day starts a fresh log.

## Reading it: what did it spend today?

```bash
# every action today, in the order it happened
jq -c --arg d "$(date -u +%Y-%m-%d)" 'select(.ts | startswith($d))' agent_actions.jsonl

# what it spent today, summed across all actions
jq -s --arg d "$(date -u +%Y-%m-%d)" 'map(select(.ts | startswith($d)) | .cost // 0) | add' agent_actions.jsonl

# every failure in one run, with the agent's reason
jq 'select(.run_id=="a1b2c3" and .status!="ok") | {ts,step,tool,reason}' agent_actions.jsonl

# the full story of one run, oldest step first
jq -s 'map(select(.run_id=="a1b2c3")) | sort_by(.step)' agent_actions.jsonl
```

Four one-liners answer the three incident questions from a shell, even over SSH from your phone. No dashboard required, and no trust in the agent's own summary of itself.

## The checklist

One action, one line, written the moment the action finishes:

- [ ] Timestamp in UTC, ISO 8601, with milliseconds
- [ ] A run id that groups the whole job, plus a step number inside it
- [ ] The tool name and its inputs, redacted before the write
- [ ] A short summary of what came back
- [ ] Result status: ok, error, or timeout, never blank
- [ ] The cost of the action, recorded per action
- [ ] The reason the agent gave, short enough to read in one line
- [ ] Secrets replaced before disk, never logged raw
- [ ] Long values truncated
- [ ] Written by appending only, kept out of the agent's reach, rotated daily or by size
- [ ] You can answer what it saw, decided and did from the log alone

Wire the helper in today, before the next incident. It's a small file and a few lines of code, and the next time money moves twice you'll have the answer in one query.

**Optional tool tip (referral links).** A coding agent can also generate the log wrapper and a small script that reads the log back, which you then review. You can [try ZCode free through this invitation](https://zcode.z.ai/invite/ALWM9JUA) (complete the invitation's onboarding steps and check current eligibility and terms) or [check the Z.ai Coding Plan referral discount](https://z.ai/subscribe?ic=R0K78RJKNW) (the final price and any discount show at checkout). We may receive referral credit. Eligibility, included models and terms are set on the destination pages.

If this saved you a bad morning, a small $WURK tip on this post keeps these guides coming.
