
Recall first from The brief, evidence and design
- A sentinel is a pipeline: collect new events, parse, detect, decide, alert, commit state.
- On Ubuntu, journald stores the binary journal and rsyslog writes text copies such as auth.log; both read /dev/log.
- Matching by SYSLOG_IDENTIFIER lets logger -t sshd inject synthetic events along the same path as real ones.
Reading the stream without missing a line
5 min readYou now have the brief and the six-stage design. This lesson answers: how do you read a log stream without missing a line, and keep state that survives a restart?
1Resume the journal from a cursor
For the journal, systemd already solved the position problem. Every entry has a cursor, an opaque string that names its exact place in the log. journalctl --cursor-file=FILE reads the cursor from FILE, shows only entries after it, and writes the cursor of the last entry back to FILE at the end. It was added in systemd 242; Ubuntu 24.04 ships systemd 255, so it is available. One pass of collection is:
journalctl --cursor-file="$state_dir/journal.cursor" -o cat \
SYSLOG_IDENTIFIER=sshd SYSLOG_IDENTIFIER=kernel > "$batch"
Matches on the same field are ORed, so this collects sshd or kernel messages. -o cat prints only the message text, which is all the rules need; the journal keeps ordering and timing internally.
2Seed the position on first run
The first run is a trap. With no cursor file, journalctl shows entries according to the other options, which here means the entire history. Alerting on that is an instant storm. Seed the position before the first real pass:
journalctl -n 1 --show-cursor -o cat | sed -n 's/^-- cursor: //p' \
> "$state_dir/journal.cursor"
--show-cursor prints the cursor after the last entry, prefixed with -- cursor:. Seeding from the newest entry means the sentinel starts watching from now, and history stays silent. Make this an explicit, documented policy, not an accident.
3Track text files by inode and offset
For text files, you keep the position yourself. Alongside the byte offset you have consumed, you store the file's inode number, the identifier of the filesystem record that holds one file's metadata and data location; a new file at the same path gets a new inode. Each pass:
ino=$(stat -c %i "$file")
size=$(stat -c %s "$file")
if [ "$ino" != "$saved_ino" ] || [ "$size" -lt "$saved_offset" ]; then
saved_offset=0
fi
tail -c +"$((saved_offset + 1))" "$file" > "$batch"
new_offset=$((saved_offset + $(wc -c < "$batch")))
tail -c +N prints from byte N to the end. Counting the bytes you actually read, rather than trusting the earlier stat, keeps the offset correct even if the file grows mid-pass. On the very first run there is no saved row: start at the current size, the same start-from-now policy as the journal.
Why check the inode at all? Because of log rotation is the periodic renaming or truncation of a log file and the start of a fresh one, so logs do not grow forever. logrotate, run daily by cron or logrotate.timer, normally renames auth.log to auth.log.1 and creates a new empty auth.log. The path is unchanged; the inode is not. A watcher that trusts the path alone reads the new file from the old offset and silently skips its first lines.
Some programs cannot be told to reopen their log file, so logrotate offers copytruncate: copy the file, then truncate the original in place. The man page warns that logging data can be lost in the small window between copy and truncate. With rename rotation, a writer holding the old file descriptor keeps writing into the renamed file until it reopens. Neither method is free; your inode-and-size check handles both, because truncation shrinks the file below your offset.
If you build the follow-mode stretch goal, the tool choice is tail -F, not tail -f. -F means --follow=name --retry: track the path, reopen after rotation, and keep retrying if the file disappears. Plain -f follows the descriptor, so after a rename it keeps reading the old, now-rotated file and never sees the new one. journalctl -f is the journal equivalent of follow mode and needs no rotation handling at all.
Going deeperHow tail -F notices rotation
GNU tail uses inotify, the kernel's file-change notification API, when available, so a rename or create event wakes it immediately. Without inotify it polls: each iteration checks the file size, and after five unchanged iterations (the --max-unchanged-stats default) it re-stats the path to compare device and inode. That is why, on a polling system, rotation can take a few seconds to notice. If tail detects that the tracked file shrank, it prints a truncation message and resumes from byte zero. Run tail --debug to see which follow implementation your build uses. BusyBox tail is a different implementation with a smaller option set; check tail --help on the board before relying on -F there.
State that survives a restart
3 min readThe sentinel keeps three small files in its state directory, /var/lib/sentinel:
journal.cursor: the last journal cursor, one line.files.state: one line per watched file, tab-separated: path, inode, offset.cooldowns: one line per active cooldown, tab-separated: rule:key, expiry as seconds since 1970-01-01 UTC, the Unix epoch.
Every write follows the same rule: write a temporary file in the same directory, then mv -f it over the old one. Rename within one filesystem is atomic: a reader sees either the complete old file or the complete new one, never a half-written mix. A crash mid-write leaves the previous state intact. This is idempotency from S09A, the rule that repeating an operation changes nothing further, applied to persistence: running a pass twice, or dying and rerunning it, must not corrupt the position.
Ordering is a real design decision. If you alert first and commit state second, a crash between the two re-alerts the same events on the next run: at-least-once delivery. If you commit first and alert second, a crash loses the alert: at-most-once. For a security watcher, a rare duplicate is better than a silent miss, so choose at-least-once, and let the cooldown stage absorb the duplicates. Write that choice into your README; reviewers will ask.
Read position: load journal.cursor and files.state from disk.
Seek: journalctl --cursor-file starts strictly after the saved cursor; tail -c starts at the saved offset.
Collect: only events written since the last committed pass arrive in the batch.
Decide: even if a crash replays a few events, their cooldown keys are still active, so no second alert.
Commit: the new position and cooldowns land atomically; the cycle repeats.
Two embedded constraints shape the state design. First, flash wear: commit only when the position actually changed, not on a fixed heartbeat, and keep the files tiny. A quiet board should write a few hundred bytes per minute at most. Second, the lock file belongs in the state directory or under /run, a RAM-backed filesystem (tmpfs) on most systems; never build a locking scheme that needs cleanup after a crash. flock releases automatically when the process dies, as the next sections use.
Going deeperWhen the journal forgets
The journal does not keep everything forever. journald rotates and vacuums its files by size and age, and journalctl --vacuum-time=2weeks deletes archived files older than two weeks. If your saved cursor points into a deleted file, the seek can fail or skip entries; the exact behaviour depends on the systemd version, so test it in the lab by vacuuming past your cursor. The robust pattern: detect the failure, log a warning that a gap occurred, reseed the cursor from the newest entry, and continue. A watcher that silently pretends nothing happened is worse than one that admits it missed a window. The same reseed logic covers a corrupted state file: validate on load, and fall back to start-from-now with a loud log line.
Key takeaways
- journalctl --cursor-file resumes where the last pass stopped; seed it on first run or you alert on all history.
- For text files, store inode plus offset; a changed inode or a shrunken file means rotation.
- tail -F follows the name and retries; tail -f holds the old descriptor and goes silent after rename rotation.
- Commit state atomically with write-temp-then-rename, and let cooldowns absorb the occasional duplicate.
Reflect
- Explain to a colleague, in two sentences: read Ubuntu's journal and text logs with journalctl and tail, and explain how rotation changes what a follower sees.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagelogrotate(8): rotates, compresses and mails system logs
- Official docstail invocation, GNU coreutils manual
Official documentation first. Links checked when the lesson was published.