# System logging

> Read and filter the systemd journal, write rsyslog rules with facilities and priorities, and keep logs from filling the disk with logrotate.

Source: https://aminbytes.dev/bytes/essential-system-services/system-logging/


When something breaks, the logs are where you find out why. A service that won't start, a disk throwing errors, someone guessing passwords over SSH: it's all written down somewhere. Knowing where logs go, how to search them and how to keep them from filling the disk is daily work for an admin, and this objective carries a lot of exam weight.

Modern Linux has two logging systems side by side: the **systemd journal** (binary, queried with `journalctl`) and a **syslog daemon**, usually **rsyslog**, which writes plain text files in `/var/log/`. You need both.

## How the pieces fit together

```text
 programs, services, kernel
           │
           ▼
   systemd-journald ──────────► /run/log/journal/  (volatile)
           │                    /var/log/journal/  (persistent)
           │ forwards or is read by
           ▼
        rsyslog ──────────────► /var/log/syslog, /var/log/messages, ...
           │
           └──────────────────► a remote log server (UDP/TCP port 514)
```

- **systemd-journald** catches everything: kernel messages, service output (stdout and stderr), and anything sent to the syslog socket.
- **rsyslog** gets those messages in one of two ways. Either journald forwards them to the syslog socket (`ForwardToSyslog=yes`, the Debian and Ubuntu setup, rsyslog's `imuxsock` module listens), or rsyslog pulls them from the journal itself with its `imjournal` module (the RHEL setup).

Debian 12 no longer installs rsyslog by default: it relies on a persistent journal. Ubuntu 24.04 and RHEL 9 still ship rsyslog.

## What's in /var/log/

| File | Contains |
| --- | --- |
| `/var/log/syslog` (Debian/Ubuntu), `/var/log/messages` (RHEL) | General system messages |
| `/var/log/auth.log` (Debian/Ubuntu), `/var/log/secure` (RHEL) | Logins, sudo, SSH |
| `/var/log/kern.log` | Kernel messages (Debian/Ubuntu) |
| `/var/log/mail.log`, `/var/log/maillog` | Mail server |
| `/var/log/cron.log`, `/var/log/cron` | Cron jobs |
| `/var/log/dpkg.log`, `/var/log/dnf.log` | Package installs |
| `/var/log/wtmp`, `/var/log/btmp`, `/var/log/lastlog` | Binary login records: read them with `last`, `lastb`, `lastlog` |
| `/var/log/journal/` | The persistent systemd journal |

Text logs are read with the usual tools:

```bash
sudo tail -f /var/log/syslog
sudo grep "Failed password" /var/log/auth.log
```

## Facilities and priorities

Every syslog message carries two labels. The **facility** says which part of the system sent it. The **priority** (severity) says how serious it is.

| Facility | Used by |
| --- | --- |
| `kern` | The kernel |
| `user` | Ordinary programs (the default) |
| `mail` | Mail system |
| `daemon` | System services without their own facility |
| `auth`, `authpriv` | Security and logins (`authpriv` may hold private data) |
| `syslog` | The syslog daemon itself |
| `lpr` | Printing |
| `cron` | cron and at |
| `news`, `uucp`, `ftp` | Old services |
| `local0` to `local7` | Free for your own programs |

Priorities, from most to least severe, with their numbers:

| # | Priority | Meaning |
| --- | --- | --- |
| 0 | `emerg` (`panic`) | System is unusable |
| 1 | `alert` | Act right now |
| 2 | `crit` | Critical condition |
| 3 | `err` (`error`) | Error |
| 4 | `warning` (`warn`) | Warning |
| 5 | `notice` | Normal but worth noting |
| 6 | `info` | Informational |
| 7 | `debug` | Debug detail |

A handy mnemonic for the order: "**E**very **A**lley **C**at **E**ats **W**hen **N**ot **I**n **D**anger".

## rsyslog rules

rsyslog's main config is **`/etc/rsyslog.conf`**, and it includes every file in `/etc/rsyslog.d/*.conf`. Put your own rules in a new file there. Each rule is a **selector** (facility.priority) and an **action**:

```text {title="/etc/rsyslog.conf (RHEL 9, rules part)"}
*.info;mail.none;authpriv.none;cron.none                /var/log/messages
authpriv.*                                              /var/log/secure
mail.*                                                  -/var/log/maillog
cron.*                                                  /var/log/cron
*.emerg                                                 :omusrmsg:*
local7.*                                                /var/log/boot.log
```

```text {title="/etc/rsyslog.d/50-default.conf (Ubuntu, rules part)"}
auth,authpriv.*                 /var/log/auth.log
*.*;auth,authpriv.none          -/var/log/syslog
kern.*                          -/var/log/kern.log
mail.*                          -/var/log/mail.log
mail.err                        /var/log/mail.err
*.emerg                         :omusrmsg:*
```

### Selector syntax

| Selector | Matches |
| --- | --- |
| `mail.info` | mail at `info` **or higher** |
| `mail.=info` | mail at exactly `info` |
| `mail.!info` | mail **below** `info` (excludes info and higher) |
| `mail.*` | all mail messages |
| `mail.none` | no mail messages (used to exclude) |
| `auth,authpriv.*` | several facilities, comma separated |
| `*.info;mail.none` | several selectors, semicolon separated: all info+, but no mail |

### Actions

| Action | Effect |
| --- | --- |
| `/var/log/file` | Append to a file |
| `-/var/log/file` | Same, without syncing after every line (old syntax, faster) |
| `@logserver.example.com` | Send over UDP, port 514 |
| `@@logserver.example.com:514` | Send over TCP |
| `:omusrmsg:*` | Write to every logged-in user's terminal (old syntax: `*`) |
| `:omusrmsg:root,amin` | Write to those users' terminals |
| `\|/path/to/fifo` | Write into a named pipe |
| `stop` | Discard the message (old syntax: `~`) |

Here's a small custom rule set. It keeps your app's messages in their own file and sends everything else to a central log server:

```text {title="/etc/rsyslog.d/30-myapp.conf"}
local3.*        /var/log/myapp.log
& stop
*.*             @@logs.example.com:514
```

`&` repeats the previous selector, so `& stop` means "and don't process local3 messages any further". Check the syntax and reload:

```bash
sudo rsyslogd -N1               # validate the config
sudo systemctl restart rsyslog
```

To make a machine **receive** logs, load an input module:

```text {title="/etc/rsyslog.d/10-receive.conf"}
module(load="imudp")
input(type="imudp" port="514")
module(load="imtcp")
input(type="imtcp" port="514")
```

Older configs write the same thing as `$ModLoad imudp` and `$UDPServerRun 514`. You'll see both styles.

## Sending test messages with logger

**logger** writes a syslog message from the shell. It's perfect for testing rules and for logging from scripts:

```bash
logger "Backup started"
logger -p local3.warning -t myapp "Disk is 90% full"
tail -n 2 /var/log/myapp.log
```

```console
2026-12-01T14:31:07.118204+01:00 web1 myapp: Disk is 90% full
```

`-p` sets facility.priority (default `user.notice`) and `-t` the tag shown before the message.

## The systemd journal with journalctl

journald stores structured, indexed, binary logs. You read them with **journalctl**. Regular users only see their own messages, unless they're in the `systemd-journal`, `adm` or `wheel` group. Use `sudo` to see everything.

```bash
journalctl                  # everything, oldest first, in a pager
journalctl -e               # jump to the end
journalctl -r               # newest first
journalctl -n 20            # last 20 lines
journalctl -f               # follow, like tail -f
journalctl -k               # kernel messages only, like dmesg
journalctl -x               # add help text to known messages
```

### Filtering by boot, service, priority and time

```bash
journalctl -b                         # this boot
journalctl -b -1                      # the previous boot
journalctl --list-boots               # all boots the journal knows

journalctl -u ssh.service             # one unit (sshd.service on RHEL)
journalctl -u nginx -u php-fpm        # several units
journalctl -t myapp                   # by syslog tag (from logger -t or systemd-cat -t)
journalctl _PID=1234                  # by any journal field
journalctl /usr/sbin/sshd             # by executable

journalctl -p err                     # err and worse (crit, alert, emerg)
journalctl -p warning..err            # a range
journalctl -p 3 -b                    # numbers work too

journalctl --since "2026-12-01 09:00" --until "2026-12-01 10:00"
journalctl --since yesterday
journalctl --since "1 hour ago"
journalctl -u cron --since today -p warning
```

Filters combine: the last line shows warnings and worse from cron, since midnight.

```console
Dec 01 09:12:44 web1 CRON[18233]: (root) ERROR (getpwnam() failed)
```

### Output formats

```bash
journalctl -u ssh -o short-iso        # ISO timestamps
journalctl -u ssh -o verbose          # every field of every entry
journalctl -u ssh -o json-pretty      # JSON, for scripts
journalctl -u ssh -o cat              # just the message text
```

`-o verbose` shows the hidden fields you can filter on, such as `_SYSTEMD_UNIT`, `_COMM`, `_UID` and `PRIORITY`.

## Writing to the journal with systemd-cat

**systemd-cat** connects a command's output to the journal. Pipe text into it, or run a command through it:

```bash
echo "Nightly report done" | systemd-cat -t report -p info
systemd-cat -t backup /usr/local/bin/backup.sh
journalctl -t report -n 1
```

```console
Dec 01 14:35:02 web1 report[20412]: Nightly report done
```

Both `logger` and `systemd-cat` end up in the journal. `logger` speaks syslog, so rsyslog sees it the same way. `systemd-cat` writes to the journal directly.

## Persistent storage and journal size

The journal's settings live in **`/etc/systemd/journald.conf`**, in the `[Journal]` section. Every line starts commented out with its default value. You can also put overrides in `/etc/systemd/journald.conf.d/*.conf`.

The `Storage=` option decides where the journal goes:

| Value | Behaviour |
| --- | --- |
| `volatile` | Only in RAM, under `/run/log/journal/`. Lost at reboot. |
| `persistent` | On disk in **`/var/log/journal/`**, created if missing. |
| `auto` (default) | On disk **if `/var/log/journal/` exists**, otherwise in RAM. |
| `none` | Keep nothing (forwarding to syslog still works). |

So there are two ways to make the journal survive reboots:

```bash
# Option 1: just create the directory (works with Storage=auto)
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo systemctl restart systemd-journald

# Option 2: set it explicitly
sudo mkdir -p /etc/systemd/journald.conf.d
printf '[Journal]\nStorage=persistent\n' | sudo tee /etc/systemd/journald.conf.d/persistent.conf
sudo systemctl restart systemd-journald
```

Size limits go in the same file:

```text {title="/etc/systemd/journald.conf.d/size.conf"}
[Journal]
SystemMaxUse=500M        # max disk space for /var/log/journal
SystemKeepFree=1G        # always leave this much free
SystemMaxFileSize=50M    # size of one journal file before rotating
RuntimeMaxUse=100M       # the same limit for /run/log/journal
MaxRetentionSec=1month   # drop entries older than this
```

By default, `SystemMaxUse` is 10% of the file system, capped at 4 GB.

## Deleting old journal data

Check how much space the journal uses, then **vacuum** it:

```bash
journalctl --disk-usage
sudo journalctl --vacuum-size=200M     # shrink to 200 MB
sudo journalctl --vacuum-time=2weeks   # drop entries older than two weeks
sudo journalctl --vacuum-files=5       # keep only 5 archived files
```

```console
Archived and active journals take up 1.2G in the file system.
Vacuuming done, freed 1.0G of archived journals from /var/log/journal/3f1c...
```

Vacuuming only removes **archived** files, never the active one. Run `sudo journalctl --rotate` first (or in the same command) to archive the active file.

## Reading a journal from a rescue system

If a machine won't boot, start a rescue system (a live USB, or the rescue image of your cloud provider), mount the broken root file system, and point journalctl at it:

```bash
sudo mount /dev/sda2 /mnt
journalctl -D /mnt/var/log/journal -b -1 -p err     # --directory
journalctl --root=/mnt -b -1                        # treat /mnt as the root
journalctl --file=/mnt/var/log/journal/*/system.journal
```

The journal files sit in a subdirectory named after the machine ID (`/etc/machine-id`). This only works if the journal was persistent, which is another reason to turn it on. You can also copy that directory to another machine and read it there with `-D`. (Side note: Journal files are append-only and carry checksums, so `journalctl --verify` can tell you whether a file was damaged or tampered with.)

## Rotating text logs with logrotate

Text logs grow forever unless something trims them. **logrotate** renames the current log (`syslog` becomes `syslog.1`), starts a new one, compresses older copies and deletes the oldest. It runs once a day, from `logrotate.timer` on systemd distributions or `/etc/cron.daily/logrotate` on older ones.

The global defaults are in **`/etc/logrotate.conf`**, and each package drops its own rules in **`/etc/logrotate.d/`**:

```text {title="/etc/logrotate.conf"}
weekly
rotate 4
create
dateext                  # RHEL default: name copies syslog-20261201 instead of syslog.1
include /etc/logrotate.d
```

```text {title="/etc/logrotate.d/myapp"}
/var/log/myapp.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0640 root adm
    postrotate
        systemctl kill -s HUP rsyslog.service >/dev/null 2>&1 || true
    endscript
}
```

| Directive | Meaning |
| --- | --- |
| `daily`, `weekly`, `monthly`, `yearly` | How often to rotate |
| `size 100M` | Rotate when bigger than this, regardless of time |
| `rotate 7` | Keep 7 old copies, delete older ones |
| `compress`, `delaycompress` | gzip old copies, but leave the newest copy uncompressed for one more round |
| `missingok`, `notifempty` | No error if the log is missing, skip empty logs |
| `create 0640 root adm` | Make the new empty log with these permissions and owner |
| `copytruncate` | Copy the log, then empty it in place (for programs that can't reopen their log) |
| `postrotate` ... `endscript` | Commands to run after rotating, usually telling the program to reopen its file |

Test without changing anything, then force a run:

```bash
sudo logrotate -d /etc/logrotate.conf          # debug: shows what it would do
sudo logrotate -f /etc/logrotate.d/myapp       # force a rotation now
sudo logrotate -v /etc/logrotate.conf          # verbose real run
```

logrotate remembers when it last rotated each file in `/var/lib/logrotate/status` (Debian) or `/var/lib/logrotate/logrotate.status` (RHEL).

## syslog, syslog-ng and rsyslog

You only need to know these exist:

- **syslog** (sysklogd) is the original: `syslogd` plus `klogd` for kernel messages, configured in `/etc/syslog.conf`. rsyslog kept its selector syntax, so old configs still read the same.
- **syslog-ng** ("next generation") is an alternative with its own syntax of `source`, `filter`, `destination` and `log` blocks in `/etc/syslog-ng/syslog-ng.conf`. It's common on SUSE and in larger log setups.
- **rsyslog** ("rocket-fast") is the default syslog daemon on Debian, Ubuntu, RHEL and Fedora, with extra modules for TCP, TLS, databases and more.

## Exam checklist

- Know the facilities (`kern user mail daemon auth authpriv syslog lpr cron local0-7`) and the 8 priorities in order, `emerg` (0) to `debug` (7).
- `facility.priority` means that priority **and higher**. `=` means exactly, `!` excludes, `none` excludes a facility, `*` matches all.
- Actions: a file, `-file` (no sync), `@host` (UDP 514), `@@host` (TCP), `:omusrmsg:*` (all users), `stop`. Config in `/etc/rsyslog.conf` and `/etc/rsyslog.d/`.
- `logger -p local0.err -t tag "msg"` and `systemd-cat -t tag -p err command` write test messages.
- `journalctl` filters: `-b`, `-u unit`, `-p prio`, `--since`/`--until`, `-k`, `-f`, `-n`, `-t`, `-o`.
- Persistent journal: `/var/log/journal/` plus `Storage=auto` (default), or `Storage=persistent` in `/etc/systemd/journald.conf`. Size: `SystemMaxUse=`.
- Clean up with `journalctl --vacuum-size`, `--vacuum-time`, `--vacuum-files`. Check with `--disk-usage`.
- From a rescue system: `journalctl -D /mnt/var/log/journal` or `--root=/mnt` or `--file=`.
- rsyslog gets journal messages through forwarding to the syslog socket (`ForwardToSyslog=`) or the `imjournal` module.
- logrotate: `/etc/logrotate.conf`, `/etc/logrotate.d/`, directives `rotate`, `compress`, `missingok`, `notifempty`, `create`, `postrotate`. Test with `logrotate -d`.


## Byte check

1. Which rsyslog selector matches mail messages of priority `warning` **and everything more severe**?
   - `mail.=warning`
   - **`mail.warning`** (correct)
   - `mail.!warning`
   A plain priority means "this one and higher". `=` limits it to exactly that priority, and `!` excludes it and everything above.

2. The journal on this machine is gone after every reboot. What makes it persistent?
   - **Set `Storage=persistent` in `/etc/systemd/journald.conf` (or create `/var/log/journal/`) and restart systemd-journald** (correct)
   - Run `journalctl --flush` once
   - Add `*.* /var/log/journal` to `/etc/rsyslog.conf`
   With the default `Storage=auto`, journald only writes to disk when `/var/log/journal/` exists. `Storage=persistent` creates it for you.

3. You booted a rescue system and mounted the broken root file system on `/mnt`. How do you read its journal?
   - `journalctl -b -1`
   - `journalctl -u /mnt`
   - **`journalctl -D /mnt/var/log/journal`** (correct)
   `-D` (`--directory`) reads journal files from another directory. `-b -1` would read the rescue system's own previous boot.


