Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

LX
Linux
0/11 completed
Beginner
The Linux file systemUsers, groups and permissionsPackage managers
Intermediate
Processes and signalsDisks, storage and archivesNetworking commandsSSH and remote access
Advanced
systemd and servicesLogs and troubleshooting
Pro
Securing a serverPerformance and resource limits
Tracks / Linux / Advanced

Logs and troubleshooting

When something breaks on a server, the answer is almost always in a log. This lesson shows where logs live, how to search them quickly with journalctl and the classic text tools, how to keep them from filling the disk, and a step-by-step routine for figuring out what went wrong.

Two kinds of logs

Where What Read with
The journal (systemd-journald) Everything systemd services print, plus the kernel and system messages journalctl
Files in /var/log Apps that write their own files: nginx, PostgreSQL, apt, and syslog copies tail, less, grep
bash
sudo systemctl start nginx
ls /var/log | head -12
Output
README
alternatives.log
apt
bootstrap.log
btmp
dmesg
dpkg.log
faillog
journal
lastlog
nginx
private
File Contains
/var/log/syslog (Debian/Ubuntu), /var/log/messages (RHEL) General system messages
/var/log/auth.log (RHEL: secure) Logins, sudo, SSH
/var/log/nginx/access.log, error.log Every web request, and web-server errors
/var/log/apt/history.log What was installed or upgraded, and when
/var/log/kern.log, dmesg Kernel messages: hardware, disks, out-of-memory kills

journalctl

Let's create some log entries first, with a service that logs at different levels:

bash
cat > /usr/local/bin/orders-worker <<'EOF'
#!/usr/bin/env bash
echo "<6>worker started"
for i in 1 2 3; do echo "<6>processed order $i"; done
echo "<4>order 4: payment provider slow (2.8s)"
echo "<3>order 5: payment failed: card declined"
echo "<6>worker idle"
sleep infinity
EOF
chmod +x /usr/local/bin/orders-worker
systemd-run --unit=orders --quiet /usr/local/bin/orders-worker
sleep 1
logger -t backup "nightly backup finished: 2.1 GB"
echo "started"
Output
started

(systemd-run starts a temporary service without writing a unit file. The <3>, <4>, <6> prefixes tell the journal the priority of each line: error, warning, info. logger writes a message to the journal from any script.)

bash
journalctl -u orders --no-pager -o cat
Output
Started orders.service - /usr/local/bin/orders-worker.
worker started
processed order 1
processed order 2
processed order 3
order 4: payment provider slow (2.8s)
order 5: payment failed: card declined
worker idle

The everyday options:

bash
echo "--- only warnings and worse:"
journalctl -u orders -p warning --no-pager -o cat
echo "--- search across all services:"
journalctl --since "10 min ago" --grep "backup|payment" --no-pager -o cat
echo "--- one line as JSON:"
journalctl -u orders -n 1 -o json --no-pager | jq -c '{unit: ._SYSTEMD_UNIT, priority: .PRIORITY, message: .MESSAGE}'
Output
--- only warnings and worse:
order 4: payment provider slow (2.8s)
order 5: payment failed: card declined
--- search across all services:
Started dpkg-db-backup.timer - Daily dpkg database backup timer.
order 4: payment provider slow (2.8s)
order 5: payment failed: card declined
nightly backup finished: 2.1 GB
--- one line as JSON:
{"unit":"orders.service","priority":"6","message":"worker idle"}
Option Shows
-u nginx One service (repeat -u for several)
-f Follow new lines as they arrive (like tail -f)
-n 50 The last 50 lines
-e Jump to the end in the pager
-p err Priority err and worse (emerg, alert, crit, err, warning, notice, info, debug)
--since "1 hour ago", --since today, --since "2026-11-22 09:00" --until "10:00" A time range
-b / -b -1 This boot / the previous boot (what happened before that crash?)
-k Kernel messages only
--grep "regex" Search the messages
-o cat / -o short-iso / -o json Message only / with ISO dates / everything as JSON
--disk-usage, --vacuum-size=500M How much space the journal uses / shrink it

💡 journalctl -u myapp -f in one terminal while you reproduce the problem in another is the single most useful debugging habit on a server.

Log files with classic tools

bash
for path in / /about /missing /api/orders / /about /missing; do curl -s -o /dev/null "http://localhost$path"; done
tail -3 /var/log/nginx/access.log | sed -E 's/\[[^]]+\]/[DATE]/'
echo "--- status codes:"
awk '{ print $9 }' /var/log/nginx/access.log | sort | uniq -c | sort -rn
echo "--- most requested missing pages:"
awk '$9 == 404 { print $7 }' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -3
Output
::1 - - [DATE] "GET / HTTP/1.1" 200 615 "-" "curl/8.5.0"
::1 - - [DATE] "GET /about HTTP/1.1" 404 162 "-" "curl/8.5.0"
::1 - - [DATE] "GET /missing HTTP/1.1" 404 162 "-" "curl/8.5.0"
--- status codes:
      5 404
      2 200
--- most requested missing pages:
      2 /missing
      2 /about
      1 /api/orders

tail -f /var/log/nginx/access.log follows the file live; tail -F keeps following even after the file is rotated. less +F file does the same and lets you press Ctrl + C to scroll back. For the full toolbox, see Text processing: grep, sed and awk in the Bash track.

Log rotation

Log files grow forever unless something rotates them: renames the current file, starts a fresh one, compresses old ones and deletes the oldest. On most systems that's logrotate, run daily by a systemd timer. Each app drops a config into /etc/logrotate.d/:

bash
cat /etc/logrotate.d/nginx | head -9
Output
/var/log/nginx/*.log {
	daily
	missingok
	rotate 14
	compress
	delaycompress
	notifempty
	create 0640 www-data adm
	sharedscripts

Here's one for our own app's log file, tested for real:

bash
mkdir -p /var/log/shop
seq 1 5000 | sed 's/^/request /' > /var/log/shop/app.log
cat > /etc/logrotate.d/shop <<'EOF'
/var/log/shop/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
EOF
logrotate --force /etc/logrotate.d/shop
echo "new line after rotation" >> /var/log/shop/app.log
ls -1 /var/log/shop
wc -l < /var/log/shop/app.log.1
Output
app.log
app.log.1
5000
Option Meaning
daily / weekly / size 100M When to rotate
rotate 14 Keep 14 old files
compress + delaycompress gzip old files, but leave the newest old one uncompressed (the app may still be finishing writes to it)
copytruncate Copy then empty the file, for apps that can't reopen their log. The alternative is postrotate with a reload command, as nginx's config does

The journal rotates itself; set limits like SystemMaxUse=1G in /etc/systemd/journald.conf.

A troubleshooting routine

When something "doesn't work", go through the same steps every time instead of guessing:

bash
sudo systemctl start shop 2>/dev/null; true
echo "1. Is it running?"
systemctl is-active orders
echo "2. What did it say last?"
journalctl -u orders -p err -n 1 --no-pager -o cat
echo "3. Any recent errors anywhere?"
journalctl -p err --since "15 min ago" --no-pager -o cat | sort -u | head -3
echo "4. Is the disk full?"
df -h / | awk 'NR == 2 { print $5 " used" }'
echo "5. Is memory exhausted / was something killed?"
free -m | awk 'NR == 2 { print $7 " MB available" }'
journalctl -k --grep "Out of memory" --no-pager -q | wc -l
echo "6. Is it listening?"
sudo ss -tlnp | grep -c ":80 "
Output
1. Is it running?
active
2. What did it say last?
order 5: payment failed: card declined
3. Any recent errors anywhere?
order 5: payment failed: card declined
4. Is the disk full?
7% used
5. Is memory exhausted / was something killed?
6237 MB available
0
6. Is it listening?
2
  1. Is it running? systemctl status app. Failed, restarting in a loop, or not enabled?
  2. What did it log? journalctl -u app -n 100, or the app's log file. Read the first error, not the last: later errors are often side effects.
  3. What changed? A deploy, a config edit, an apt upgrade (check /var/log/apt/history.log), an expired certificate?
  4. Resources: disk (df -h, df -i), memory (free -m), CPU (top). A process killed for using too much memory leaves an "Out of memory: Killed process" line in journalctl -k.
  5. Network: is it listening (ss -tlnp), on the right address, and allowed through the firewall? See Networking commands.
  6. Permissions: run the command as the service's user: sudo -u www-data cat /srv/app/config.yml. "Permission denied" in a log is usually a file owned by the wrong user.
  7. Reproduce it by hand: run the exact ExecStart= command in a terminal with the same user and environment and watch what it prints.

Example: a service that won't start

bash
cat > /etc/systemd/system/broken.service <<'EOF'
[Service]
ExecStart=/usr/bin/python3 /opt/broken/app.py
EOF
systemctl daemon-reload
systemctl start broken; sleep 1
systemctl is-active broken
journalctl -u broken --no-pager -o cat | grep -v "^Started\|^broken.service: \(Main\|Failed\)" | head -3
Output
failed
/usr/bin/python3: can't open file '/opt/broken/app.py': [Errno 2] No such file or directory

The journal says exactly what's wrong: the file doesn't exist. Status failed + the log's first error line solve most problems in under a minute.

Practice

  1. Show the last 20 log lines of the ssh service, then only today's lines with priority warning or worse.
  2. Use logger -t myscript "hello" in a script and find the message with journalctl -t myscript.
  3. From an nginx access log, print the 5 IP addresses with the most requests.
  4. Write a logrotate config that keeps 7 compressed daily copies of /var/log/myapp/*.log and test it with logrotate --debug.
✎ Check your understanding

1.How do you follow a service's logs live?

2.A service crashed and a reboot happened. How do you see the logs from before the reboot?

3.What does logrotate do?

4.In a long log of errors, which one usually matters most?

← systemd and services