Every Linux server keeps two kinds of logs: the systemd journal, a structured binary store read with journalctl, and text files in /var/log, written by rsyslog or by applications. Running them well means keeping the journal across reboots, rotating files before they fill the disk, keeping clocks in sync so timestamps mean something, and shipping copies off the host. This lesson follows one error line from the application to the central log store, and the two ways logs fail when you need them most.
Difficulty: Intermediate · Know this first: Lesson 15, Lesson 16
This bar adds up the minutes to find one error during an incident. It is a worked example, not a measurement. The rotation and clock hops are where logs cause or hide the problem.
After rotation without a reopen, the app keeps writing to a file nobody can see. Set the disk's free space and the log rate.
Hidden growth: the disk fills in 20 days, and du will not show why
Three questions. No score is saved anywhere — this is just you against the material.
Log administration grows in four levels: reading logs, configuring the journal and rotation, forwarding and time, and logging for a fleet.
At the basic level you can find what a service said.
journalctl -u app -b, -f, -p err, --since "1 hour ago".tail -f /var/log/syslog, zgrep pattern /var/log/syslog.*.gz.logger "hello" to write a test line.Where it breaks: searching the files for a service that only logs to the journal, or the other way round.
Try it: Basic
Which command shows only errors from the app service since this boot?
Now do it: Run journalctl -p err -b on a server and read the top five sources.
At the intermediate level logs cannot fill the disk or vanish at reboot.
Storage=persistent and SystemMaxUse= in a journald drop-in; journalctl --vacuum-size=1G.daily, rotate 7, compress, delaycompress, postrotate with a reopen signal.logrotate -d to test; lsof +L1 to find deleted open files.Try it: Intermediate
Which logrotate option lets an app that cannot reopen its file keep working?
Now do it: Write a logrotate rule for one app log and dry-run it with logrotate -d.
At the advanced level logs leave the host reliably and in the right order.
chronyc tracking, makestep at boot, alerts on offset; UTC everywhere.Try it: Advanced
Why forward logs over TCP with a disk-assisted queue instead of plain UDP syslog?
Now do it: Check whether your hosts forward over UDP or TCP.
At the master level logging is a platform with budgets.
Trade-off: keeping everything is expensive and slow to search; sampling or dropping debug lines saves money and can hide the one line you needed.
Try it: Master
Central logging costs are doubling yearly. What is the most effective first step?
Now do it: Find the top three log producers on one host with journalctl -o json and a count by unit.
Make the journal persistent, rotate an app log correctly, check time sync, and find a deleted file that is still being written.
sudo mkdir -p /etc/systemd/journald.conf.d printf "[Journal]\nStorage=persistent\nSystemMaxUse=2G\n" | sudo tee /etc/systemd/journald.conf.d/50-persist.conf sudo systemctl restart systemd-journald journalctl --disk-usage; journalctl --list-boots | tail -3
/var/log/app/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
postrotate
systemctl kill -s HUP app.service
endscript
}
# test without changing anything
sudo logrotate -d /etc/logrotate.d/app
timedatectl chronyc tracking | grep -E "System time|Leap status" # a deleted file still held open, with its size sudo lsof +L1 2>/dev/null | awk 'NR == 1 || $7 > 100000000'
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A log file took down the database it was logging for.
Apps log to stdout and the journal, which is capped; remaining file logs need a reviewed rotation rule with a reopen; /var/log moved to its own volume; disk alerts include a check for large deleted open files.
Query the systemd journal, forward logs with rsyslog, and keep disks from filling with logrotate. The journal reads your own machine, so those commands are shown; you practise on a saved JSON export of the journal with jq, and run logrotate for real on files in your folder. There are 19 commands below, in the order you would use them. Each one shows what it printed when we ran it, so you can compare your screen with it; where the output depends on your machine, the note tells you what to look for.
Every command below works on these files, so run this first, in an empty folder (mkdir -p ~/practice && cd ~/practice). It only creates files there.
cat > journal.json <<'EOF'
{"_SYSTEMD_UNIT":"nginx.service","PRIORITY":"6","MESSAGE":"GET /health 200","_PID":"812"}
{"_SYSTEMD_UNIT":"app.service","PRIORITY":"3","MESSAGE":"db timeout after 5s","_PID":"1402"}
{"_SYSTEMD_UNIT":"app.service","PRIORITY":"4","MESSAGE":"retrying (1/3)","_PID":"1402"}
{"_SYSTEMD_UNIT":"sshd.service","PRIORITY":"5","MESSAGE":"Failed password for root from 203.0.113.9","_PID":"640"}
{"_SYSTEMD_UNIT":"sshd.service","PRIORITY":"5","MESSAGE":"Failed password for root from 203.0.113.9","_PID":"641"}
{"_SYSTEMD_UNIT":"app.service","PRIORITY":"3","MESSAGE":"db timeout after 5s","_PID":"1402"}
{"_SYSTEMD_UNIT":"kernel","PRIORITY":"2","MESSAGE":"Out of memory: Killed process 3120 (python3)","_PID":"0"}
EOF
mkdir -p logs
for i in 1 2 3; do echo "line $i" >> logs/app.log; done
echo "x" > logs/worker.log
cat > lab.logrotate <<EOF
$PWD/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
copytruncate
}
EOF
One unit, the last hour.
$ journalctl -u nginx --since "1 hour ago" --no-pagerPriority error and worse, this boot.
$ journalctl -p err -b --no-pagerFollow new lines as they arrive, like tail -f.
$ journalctl -f -u appExport entries as JSON lines, one object each, for tools like jq.
$ journalctl -u app -o json --no-pager -n 100 > journal.jsonHow much space the journal uses, and shrink it.
$ journalctl --disk-usage; sudo journalctl --vacuum-size=500MThese run on the saved export in journal.json.
Errors and worse (priority 3 or lower), with the unit.
$ jq -r 'select(.PRIORITY | tonumber <= 3) | "\(._SYSTEMD_UNIT): \(.MESSAGE)"' journal.json app.service: db timeout after 5s app.service: db timeout after 5s kernel: Out of memory: Killed process 3120 (python3)
Entries per unit.
$ jq -r '._SYSTEMD_UNIT' journal.json | sort | uniq -c | sort -rn 3 app.service 2 sshd.service 1 nginx.service 1 kernel
Failed SSH logins per source address.
$ jq -r 'select(.MESSAGE | test("Failed password")) | .MESSAGE | split(" from ")[1]' journal.json | sort | uniq -c 2 203.0.113.9
The most repeated message (-s reads every line into one array first).
$ jq -s 'group_by(.MESSAGE) | map({msg: .[0].MESSAGE, n: length}) | sort_by(-.n) | .[0]' journal.json { "msg": "Failed password for root from 203.0.113.9", "n": 2 }
Kernel messages: here, the OOM killer.
$ jq -c 'select(._SYSTEMD_UNIT == "kernel")' journal.json {"_SYSTEMD_UNIT":"kernel","PRIORITY":"2","MESSAGE":"Out of memory: Killed process 3120 (python3)","_PID":"0"}
Rotate daily, keep 7, gzip old ones, and copy-then-truncate so the program can keep writing to the same file.
$ cat lab.logrotate /home/you/practice/logs/*.log { daily rotate 7 compress missingok notifempty copytruncate }
Debug mode: what logrotate would do, changing nothing.
$ logrotate -d -s state.txt lab.logrotate 2>&1 | grep -E "^(rotating pattern|considering log)" | sed "s|$PWD|.|" rotating pattern: ./logs/*.log after 1 days empty log files are not rotated, (7 rotations), old logs are removed considering log ./logs/app.log considering log ./logs/worker.log
Force a rotation now. The old log is now app.log.1.gz, and app.log is empty.
$ logrotate -f -s state.txt lab.logrotate && ls logs app.log app.log.1.gz worker.log worker.log.1.gz
The live file is empty; the rotated one still holds the old lines.
$ wc -c logs/app.log; zcat logs/app.log.1.gz 0 logs/app.log line 1 line 2 line 3
The system configuration for nginx.
$ sudo logrotate -d /etc/logrotate.conf 2>&1 | grep -A2 nginxSend every message to a central server over TCP (@@; a single @ is UDP).
$ echo '*.* @@logs.internal:6514' | sudo tee /etc/rsyslog.d/50-forward.confWrite one program's messages to their own file.
$ echo ':programname, isequal, "app" /var/log/app.log' | sudo tee /etc/rsyslog.d/40-app.confCheck the configuration, then restart.
$ sudo rsyslogd -N1 && sudo systemctl restart rsyslogWrite a test message to the system log, then find it with journalctl -t app.
$ logger -t app -p user.err "test message from logger"Each task uses the practice folder. Try it first, then open the solution to compare; there is usually more than one right answer.
With jq, print the distinct units that logged a warning or worse (priority 4 or lower), sorted.
$ jq -r 'select(.PRIORITY | tonumber <= 4) | ._SYSTEMD_UNIT' journal.json | sort -u app.service kernel
With jq, count how many entries came from PID 1402.
$ jq -s 'map(select(._PID == "1402")) | length' journal.json 3
Force a rotation of the logs and print how many .gz files now exist.
$ logrotate -f -s state.txt lab.logrotate && ls logs/*.gz | wc -l 2
With jq, print each message with its priority as a word (2 crit, 3 err, 4 warning, 5 notice, 6 info).
$ jq -r '["emerg","alert","crit","err","warning","notice","info","debug"][.PRIORITY | tonumber] + " " + .MESSAGE' journal.json info GET /health 200 err db timeout after 5s warning retrying (1/3) notice Failed password for root from 203.0.113.9 notice Failed password for root from 203.0.113.9 err db timeout after 5s crit Out of memory: Killed process 3120 (python3)
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
Is the journal persistent, and how big is it?
ls -d /var/log/journal 2>/dev/null && echo persistent || echo "volatile: lost at reboot"; journalctl --disk-usage
Write a test line and find it by priority and time.
logger -p user.err "lab test from $(hostname)"; journalctl -p err --since "-1 min" --no-pager | tail -3
Clock sync: is this host's clock trustworthy?
timedatectl | grep -E "synchronized|Time zone"; chronyc tracking 2>/dev/null | grep -E "System time|Leap" || true
Reproduce the invisible full disk: a deleted file that is still open.
python3 -c "import time; f = open('big.log', 'w'); f.write('x' * 50_000_000); f.flush(); time.sleep(60)" &
sleep 1; rm big.log; ls big.log 2>&1 | tail -1
sudo lsof +L1 2>/dev/null | grep big.log; kill $!rotation_sim.pyThis program simulates logrotate over a week for three rotation styles and shows where the bytes end up: in visible files, or in a deleted file the app still holds open. Save it as rotation_sim.py, then run it.
# rotation_sim.py
DAILY_MB = 2_000
for style in ["rename only (no reopen)", "postrotate HUP (reopen)", "copytruncate"]:
visible, hidden, handle = {"app.log": 0}, 0, "app.log"
for day in range(1, 8):
if handle == "app.log":
visible["app.log"] += DAILY_MB
else:
hidden += DAILY_MB # writes go to the renamed, later deleted file
# nightly rotation, keep 2 compressed copies (compression ignored here)
if style == "copytruncate":
visible[f"app.log.{day}"] = visible["app.log"]
visible["app.log"] = 0
else:
visible[f"app.log.{day}"] = visible.pop("app.log") if handle == "app.log" else 0
visible["app.log"] = 0
handle = "app.log" if style.startswith("postrotate") else "deleted"
for old in [k for k in visible if k.startswith("app.log.") and int(k.split(".")[-1]) <= day - 2]:
del visible[old]
print(f"{style:<25} visible {sum(visible.values()):>6,} MB, hidden in deleted open file {hidden:>6,} MB")
Run it, and you should see this output:
$ python3 rotation_sim.py rename only (no reopen) visible 0 MB, hidden in deleted open file 12,000 MB postrotate HUP (reopen) visible 4,000 MB, hidden in deleted open file 0 MB copytruncate visible 4,000 MB, hidden in deleted open file 0 MB
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/linux-logs-journald-rsyslog-logrotate && cd ~/labs/linux-logs-journald-rsyslog-logrotate) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Logs on Linux: journald, rsyslog, and logrotate", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Is the journal persistent, and how big is it?'
'Write a test line and find it by priority and time.'
'Clock sync: is this host'\''s clock trustworthy?'
'Reproduce the invisible full disk: a deleted file that is still open.'
)
step_1() {
ls -d /var/log/journal 2>/dev/null && echo persistent || echo "volatile: lost at reboot"; journalctl --disk-usage
}
step_2() {
logger -p user.err "lab test from $(hostname)"; journalctl -p err --since "-1 min" --no-pager | tail -3
}
step_3() {
timedatectl | grep -E "synchronized|Time zone"; chronyc tracking 2>/dev/null | grep -E "System time|Leap" || true
}
step_4() {
python3 -c "import time; f = open('big.log', 'w'); f.write('x' * 50_000_000); f.flush(); time.sleep(60)" &
sleep 1; rm big.log; ls big.log 2>&1 | tail -1
sudo lsof +L1 2>/dev/null | grep big.log; kill $!
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, tail, kill, rm, echo, ls, Pipes, Redirection, If...Else.Design logging for 80 Linux servers running web services, a database, and batch jobs, for a team that must investigate incidents and pass a security audit.
Where do apps write logs? How are files rotated and the journal kept? How do logs leave the host, and what if the collector is down? How long is each kind kept? How do you know clocks are right?
Say 30 GB of logs a day in total, security logs kept a year, application logs 30 days, and incidents that need search within minutes.
Apps log to stdout as JSON; journald persistent, capped at 2 GB; file logs only where unavoidable, with reviewed logrotate rules; Fluent Bit on every host with a disk buffer shipping to Loki (application, 30 days) and to a write-once bucket (security, 1 year); chrony everywhere with offset alerts; dashboards of volume per service.
Logging to stdout simplifies rotation and couples apps to the journal; file logs are portable and need rotation discipline. Long retention helps investigations and costs money; split by class instead of one rule for everything.