Track Claude Code Costs and Duration in Automated Runs
When you run Claude Code with --output-format json, every response includes metadata alongside the result that you can use to monitor your automation costs:
claude -p "Review the latest commit for issues" --output-format json
The JSON envelope always contains:
{
"result": "The commit looks good overall...",
"cost_usd": 0.0032,
"duration_ms": 4812,
"session_id": "sess_abc123",
"is_error": false
}
Extract just the cost after every CI run using jq:
output=$(claude -p "Run the security audit" --output-format json)
cost=$(echo "$output" | jq -r '.cost_usd')
echo "Audit complete. Cost: \$$cost"
Fail the build automatically if a single run costs more than expected — a signal that something has gone wrong:
if (( $(echo "$cost > 0.10" | bc -l) )); then
echo "Warning: unexpectedly high cost — check prompt or turn limits"
exit 1
fi
Log costs over time to a CSV for cumulative tracking:
echo "$(date),$(echo "$output" | jq -r '.cost_usd'),$(echo "$output" | jq -r '.duration_ms')" \
>> ci_costs.log
A single run that suddenly costs 10x the usual amount is a strong signal the prompt hit an edge case or the model got stuck in a loop. Tracking this per-run lets you catch it before it becomes a real bill.
Pair with --max-budget-usd as a hard ceiling so costs never exceed your limit even if you forget to check the log.
Per-run cost visibility is the first step to keeping Claude Code automation bills predictable.
Log in to leave a comment.
A PreToolUse hook can intercept test runner commands and filter output to show only failures, cutting thousands of tokens from Claude's context.
CLAUDE.md loads into every message. Move workflow-specific instructions into skills that load on demand to reduce token costs across your session.
Every event emitted while processing a single prompt shares a prompt.id UUID, letting you trace the complete chain of API calls and tool executions.