Sub topic 10
Keeping logs and run records
When you run an agent by hand, you watch the output and see what went wrong. In a scheduled job nobody watches, so the logs and records are your only evidence of what happened at 02:00. This chapter covers what to capture, where it goes, how long to keep it, and the mistakes that make logs useless or unsafe.
It assumes you have the wrapper script from the timeouts chapter (flock, timeout, a timestamped log, and a passed-through exit status). You should also be comfortable with jq basics and with file permissions.
Two kinds of record
A scheduled agent run produces two different things, and they need different handling.
- The raw log is everything the agent printed to stdout and stderr. It is large, noisy, and may contain sensitive text. You read it when investigating one run.
- The run record is one small structured line per run: when it started, how long it took, how it ended, and where its log is. You read it to answer questions across many runs, such as "how many failures this week?" or "when did it last succeed?"
The scheduler adds a third source, its own history (cron mail, the systemd journal, or the CI run page). Treat that one as a backup. It records that the job started and how it exited, but not the details you need.
What a run record should contain
Keep the record short and the same shape every time. These fields answer most questions:
| Field | Why it is there |
|---|---|
| `run_id` | Ties the record to its log file name. |
| `started` | UTC timestamp, so records sort correctly and ignore time zones. |
| `seconds` | Duration. A run that suddenly takes four times longer is a warning sign. |
| `outcome` | A word: `ok`, `failed`, `timeout`, or `skipped`. |
| `status` | The numeric exit status, kept for detail. |
| `commit` | The repository commit the run started from. If the prompt file lives in the repo, this also tells you which prompt version ran. |
| `log` | Path to the raw log. |
Record skipped runs too. A run skipped by the lock is not an error, but a week of nothing but skips means a job is stuck.
A wrapper that writes both
This version of the wrapper adds a write_record function. It uses jq to build the JSON, so quotes and special characters in values are escaped correctly. Hand-assembling JSON with echo breaks the first time a path contains a quote.
#!/usr/bin/env bash
# nightly-agent.sh, with run records
set -u
: "${AGENT_CMD:?set AGENT_CMD to your agent's non-interactive command}"
umask 077 # logs may contain sensitive text: owner-only access
REPO=/srv/repos/my-project
LOG_DIR="$HOME/agent-logs"
RECORDS="$LOG_DIR/runs.jsonl"
mkdir -p "$LOG_DIR"
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$"
LOG="$LOG_DIR/nightly-$RUN_ID.log"
STARTED="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
START_S="$(date +%s)"
write_record() { # usage: write_record OUTCOME STATUS
jq -cn \
--arg run_id "$RUN_ID" \
--arg started "$STARTED" \
--arg outcome "$1" \
--argjson status "$2" \
--argjson seconds "$(( $(date +%s) - START_S ))" \
--arg commit "$(git -C "$REPO" rev-parse --short HEAD 2>/dev/null || echo unknown)" \
--arg log "$LOG" \
'{run_id:$run_id, started:$started, outcome:$outcome, status:$status,
seconds:$seconds, commit:$commit, log:$log}' >> "$RECORDS"
}
exec 9>"$HOME/.nightly-agent.lock"
if ! flock -n 9; then
write_record skipped 0
exit 0
fi
cd "$REPO" || { write_record failed 1; exit 1; }
# AGENT_CMD is intentionally unquoted so a command with arguments splits into words.
timeout 20m $AGENT_CMD < prompts/nightly.md > "$LOG" 2>&1
status=$?
case "$status" in
0) outcome=ok ;;
124) outcome=timeout ;;
*) outcome=failed ;;
esac
write_record "$outcome" "$status"
exit "$status"The file format is JSON Lines: one complete JSON object per line, appended and never rewritten. Appending needs no read-modify-write cycle, so a crash cannot corrupt earlier records. Because the lock prevents overlapping runs of this job, two copies of the script will not append at the same moment.
Reading the records
Because each line is valid JSON, jq can answer questions directly:
# Every run that did not succeed or skip
jq -c 'select(.outcome == "failed" or .outcome == "timeout")' ~/agent-logs/runs.jsonl
# Average duration of successful runs, in seconds
jq -s '[.[] | select(.outcome == "ok") | .seconds] | add / length' ~/agent-logs/runs.jsonl
# Start time of the most recent success
jq -r 'select(.outcome == "ok") | .started' ~/agent-logs/runs.jsonl | tail -n 1The last query matters for the next chapter. Detecting that a job has stopped running ("alerting on silence") depends on knowing when it last succeeded.
What goes in the raw log
The wrapper redirects both stdout and stderr to one file with > "$LOG" 2>&1. That is usually what you want, because error messages and normal output stay in order.
Add context the agent will not print for itself. Writing a few header lines before the agent starts costs nothing and saves time during an investigation:
- the start time in UTC
- the working directory and the user running the job
- the agent command (without any secrets in its arguments)
If you append these lines with >> before the agent runs, use >> for the agent's output as well. The > in the wrapper above would truncate them.
Where the scheduler's own logs go
Each scheduler keeps its own history, and the defaults differ.
| Scheduler | Where output ends up | How to read it |
|---|---|---|
| cron | Mailed to the local user if a mail system exists, otherwise discarded | Redirect output in the crontab line, or rely on the wrapper's own log |
| systemd timer | The journal, under the service unit | `journalctl -u nightly-agent.service --since "2 days ago"` |
| CI schedule | The run page, kept for the provider's retention period | Open the run, or upload the log as an artifact so it outlives the page |
The cron default is a common trap. If no mail system is set up, cron output vanishes. Your wrapper's log file is the reason this does not matter, as long as the wrapper writes it by an absolute path.
Retention and rotation
Logs grow every night, and an unattended job will eventually fill a disk. Delete raw logs on a schedule, and keep the compact records longer:
# Delete raw logs older than 30 days
find "$HOME/agent-logs" -name 'nightly-*.log' -mtime +30 -deleteRun this from a second cron entry or at the end of the wrapper. Pick the window from how long you need to investigate an old failure. A run record is a few hundred bytes, so keeping a year of them is cheap.
Common errors
- Logging only on success. A job that crashes before it reaches the logging line leaves no trace. Write the record from every exit path, as
write_recorddoes for the lock andcdfailures. - Local-time timestamps. Cron uses the system's local time zone, and daylight-saving changes produce duplicate or missing hours. Use
date -uin file names and records. - Relative log paths. Under a scheduler the working directory is not your shell's. Always build log paths from an absolute directory such as
$HOME/agent-logs. - Same file name for every run. A fixed name such as
nightly.logis overwritten, which destroys the evidence of the failure you most want to see. Include the timestamp and process ID. - No retention. The disk fills, writes fail, and the job fails for a reason unrelated to the agent.
- Hand-built JSON. A single unescaped character makes a line unparseable, and every later
jqquery then fails on that line. Build records withjq -n.
Exercise
Your wrapper writes a run record only after the agent command finishes. One night the server loses power during a run. What does runs.jsonl show for that night, and how would you change the wrapper so the interruption is visible?
Show answer
It shows nothing for that run, because the record is written after the agent exits and the script never got that far. The raw log file may exist and be partial. To make the gap visible, write a record with outcome "started" before launching the agent, then write a final record with the same runid when it ends. A runid that has a "started" record but no final record was interrupted. Alternatively, the alert for silence (no success within the expected interval) will catch it indirectly.