Product case study · October 27, 2026
Claude Code Hooks: Log File Edits with PostToolUse
Build a local Claude Code edit log, test it with synthetic events, and compare a live PostToolUse record with the actual Git diff.

Use an edit-event log to guide your review, then inspect the files. A hook record alone cannot prove the change was correct or capture every way a file can change.
When an agent says it edited a file, you still need to know which tool ran and what changed. This exercise adds a small local event log to Claude Code, then pairs that record with a Git diff. The result is useful for reviewing a supervised session or diagnosing a missing edit.
Sources checked October 27, 2026. We tested the Python logger, its six synthetic cases and the local Git verification commands. We checked the installed Claude Code version, 2.1.304, but did not run an authenticated Claude editing session. The live steps below are acceptance criteria, not reported integration results.
You need Bash on Linux or macOS, Python 3, Git and an installed, authenticated Claude Code CLI. Use the synthetic file below in a fresh directory. This example is for one supervised session, not a shared audit service.
Choose what the log can tell you
Anthropic’s hooks reference describes PostToolUse as an event after successful tool execution. Command hooks receive JSON on standard input. An Edit|Write matcher selects those tool names; it does not catch changes made through Bash or an external editor. Failed tool calls have a separate event.
Our logger keeps only a timestamp, session ID, tool-use ID, tool name and file path. It deliberately omits the transcript, file contents and tool response. File paths can still reveal private project names, so keep this local and review it before sharing.
Treat the log as a review aid. It contains no before-and-after bytes, it is writable by the same user running the agent, and a successful tool event says nothing about whether the edit meets your requirements.
Prepare one disposable project
Run these commands in Bash. Keep the printed path for later inspection:
lab_root=$(mktemp -d /tmp/claude-edit-log.XXXXXX)
mkdir -p "$lab_root/project/.claude/hooks" "$lab_root/evidence"
cd "$lab_root/project"
printf 'Lab root: %s\n' "$lab_root"
printf 'Project: Lantern\nReview day: Friday\n' > notes.txt
printf '.claude/edit-events.jsonl\n' > .gitignore
git init -q
Save the following script as .claude/hooks/record-edit.py:
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
def main():
event = json.load(sys.stdin)
if not isinstance(event, dict):
raise ValueError("event must be an object")
if event.get("hook_event_name") != "PostToolUse":
return
if event.get("tool_name") not in ("Edit", "Write"):
return
tool_input = event.get("tool_input")
if not isinstance(tool_input, dict):
raise ValueError("tool_input must be an object")
fields = {
"session_id": event.get("session_id"),
"tool_use_id": event.get("tool_use_id"),
"tool_name": event["tool_name"],
"file_path": tool_input.get("file_path"),
}
if any(not isinstance(v, str) or not v.strip() for v in fields.values()):
raise ValueError("required metadata must be nonempty strings")
row = {
"recorded_at": datetime.now(timezone.utc).isoformat(),
**fields,
}
log_path = Path(__file__).resolve().parents[1] / "edit-events.jsonl"
with log_path.open("a", encoding="utf-8") as log:
log.write(json.dumps(row, ensure_ascii=True) + "\n")
try:
main()
except (ValueError, OSError) as exc:
print(f"edit logger failed: {type(exc).__name__}", file=sys.stderr)
sys.exit(1)
The script treats the supplied file path as data. It never opens that file or builds a shell command from it. JSON encoding keeps quotes and embedded newlines inside a single record. The timestamp is when the logger wrote the row, not the edit’s duration. Errors print their type without echoing the input payload.
Test the logger without calling a model
Run this from the project directory. It copies the script into a temporary test folder, so fixture records cannot be mistaken for live events in your project log.
python3 - <<'PY'
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
base = {
"hook_event_name": "PostToolUse",
"session_id": "fixture-session",
"tool_use_id": "fixture-edit",
"tool_name": "Edit",
"tool_input": {"file_path": '/tmp/notes "draft".txt',
"new_string": "DO_NOT_LOG_CONTENT"},
"tool_response": {"private": "DO_NOT_LOG_RESPONSE"},
}
cases = [
(base, 0),
({**base, "tool_name": "Write", "tool_use_id": "fixture-write"}, 0),
({**base, "tool_name": "Bash"}, 0),
({**base, "hook_event_name": "PostToolUseFailure"}, 0),
({**base, "tool_input": {}}, 1),
("not JSON", 1),
]
with tempfile.TemporaryDirectory() as tmp:
hooks = Path(tmp) / ".claude" / "hooks"
hooks.mkdir(parents=True)
script = hooks / "record-edit.py"
shutil.copyfile(".claude/hooks/record-edit.py", script)
for payload, expected_code in cases:
raw = payload if isinstance(payload, str) else json.dumps(payload)
result = subprocess.run([sys.executable, str(script)], input=raw,
text=True, capture_output=True)
assert result.returncode == expected_code, result.stderr
assert result.stdout == ""
raw_log = (hooks.parent / "edit-events.jsonl").read_text()
rows = [json.loads(line) for line in raw_log.splitlines()]
assert [r["tool_name"] for r in rows] == ["Edit", "Write"]
assert [r["tool_use_id"] for r in rows] == ["fixture-edit", "fixture-write"]
expected_keys = {"recorded_at", "session_id", "tool_use_id",
"tool_name", "file_path"}
assert all(set(r) == expected_keys for r in rows)
assert all(r["file_path"] == base["tool_input"]["file_path"] for r in rows)
assert "DO_NOT_LOG" not in raw_log
print("PASS: six synthetic cases; two metadata-only records")
PY
Do not continue if an assertion fails. This check proves that the script handles these inputs. It does not test whether Claude loads your settings or sends an event.
Register the hook and record a baseline
Create .claude/settings.json with this content:
{
"hooks": {
"PostToolUse": [
{
"matcher": "^(Edit|Write)$",
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/record-edit.py\"",
"timeout": 10
}
]
}
]
}
}
The reference documents CLAUDE_PROJECT_DIR for locating project scripts. Quoting it keeps a project path containing spaces together. The anchored matcher restricts this example to the two exact tool names. Hook configuration reference
This complete settings file belongs only in the fresh lab. When adapting it, merge the hook into existing settings instead of overwriting them. The official settings guide distinguishes project settings from user settings that affect every project; managed policy can take precedence. We use a project file to keep the experiment scoped to this folder.
Validate the JSON and commit the lab baseline with a disposable identity used only for this command:
python3 -m json.tool .claude/settings.json > /dev/null
git add notes.txt .gitignore .claude/hooks/record-edit.py .claude/settings.json
git -c user.name='Hook Lab' -c user.email='hook-lab@example.invalid' \
commit -m "Record edit logger lab baseline"
git rev-parse HEAD > "$lab_root/evidence/baseline-commit.txt"
git status --short
claude --version > "$lab_root/evidence/cli-version.txt"
claude
Require an empty status before launching. Inspect the scratch folder before accepting any workspace-trust prompt. Keep ordinary tool approvals enabled.
Inside Claude Code, run /status to inspect loaded settings sources, then /hooks to find the command under PostToolUse. The hooks guide recommends checking the event and case-sensitive matcher when a hook does not fire. If this hook is missing, fix configuration before requesting an edit; restarting can help if a settings reload was missed. Respect any managed-hooks restriction.
Request one edit and reconcile the evidence
Submit this prompt:
Read notes.txt. Use the built-in Edit tool to change only
"Review day: Friday" to "Review day: Monday". Preserve the project line
and final newline. Do not use Bash to edit files, touch .claude or
.gitignore, create other files, or make commits. Stop after this edit.
Approve only the intended change. After the response, exit Claude Code and inspect the lab from the same terminal:
git diff -- notes.txt
git status --short
python3 - <<'PY'
import json
from pathlib import Path
assert Path("notes.txt").read_bytes() == b"Project: Lantern\nReview day: Monday\n"
rows = [json.loads(line) for line in
Path(".claude/edit-events.jsonl").read_text().splitlines()]
assert len(rows) == 1, "Review extra or missing events before accepting this run"
row = rows[0]
assert row["tool_name"] == "Edit"
assert Path(row["file_path"]) == Path("notes.txt").resolve()
assert row["session_id"] and row["tool_use_id"]
print("PASS: expected file bytes and one matching Edit record")
PY
git rev-parse HEAD > "$lab_root/evidence/after-commit.txt"
cmp "$lab_root/evidence/baseline-commit.txt" "$lab_root/evidence/after-commit.txt"
git diff --exit-code -- .claude/hooks/record-edit.py .claude/settings.json .gitignore
Accept the run only when the Python checks pass, both final commands exit zero, and status shows only notes.txt modified. The ignored log is checked separately. If Claude uses multiple edits or a different tool, record that variation and inspect it; do not delete rows just to satisfy the one-event check.
Keep the diff and log outside the project after reviewing them:
git diff -- notes.txt > "$lab_root/evidence/notes.diff"
cp .claude/edit-events.jsonl "$lab_root/evidence/edit-events.jsonl"
Diagnose gaps before using the log again
| What you observe | What to check next |
|---|---|
| File changed but no log exists | Inspect which tool made the change and confirm the hook appears in /hooks. |
| A hook error appears | Run the synthetic test again; check that Python is available and the log directory is writable. |
| More than one row appears | Review tool-use IDs and session IDs for multiple edits, another session or duplicate registration. |
| Expected row exists but file bytes differ | Treat the content check as failed; inspect the diff and any later edits. |
| Hook is absent despite valid JSON | Check loaded settings sources and organizational restrictions before changing policy. |
The hooks troubleshooting guide points to Ctrl+O for hook outcomes and debug logs for more detail. A silent successful hook is normal. This logger’s exit code 1 reports an error; it does not reverse a completed edit. PostToolUse runs after the action.
To stop this lab’s logger, exit the session and remove only its PostToolUse entry from the lab settings. Retain the evidence until reviewed. For an existing project, keep other hooks intact.
Before adapting the script to concurrent workers or long-running automation, design log rotation, writer coordination and access controls. This small append-only-in-code example does not supply those guarantees. Pair any event record with the acceptance checks your coding task actually needs.
Official source notes
All checked October 27, 2026:
- Hooks reference: event timing, JSON input, tool matchers and project-script paths.
- Automate actions with hooks: setup verification, troubleshooting and the limits of post-tool hooks.
- Settings files and precedence: project scope, loaded settings sources and managed precedence.
Put this to work
Separate evidence that a file-edit tool ran from evidence that its change is correct.
Try
Install a project-local PostToolUse logger in a disposable folder and request one edit.
Prove it worked
Pass six synthetic logger cases, then match a live event to the exact changed file and diff.
Keep in view
- Record selected metadata instead of copying file contents or full tool responses.
- Test successful, ignored and malformed events before opening an agent session.
- Compare the event log with Git because shell edits do not match Edit or Write.