Sub topic 9
Taming logs with logrotate and journald limits
Logs are the most common source of runaway disk use on a server. They grow without anyone touching them, and they are usually safe to trim once you know the rules. This chapter assumes you can read df and du output, find large files with find, and know that a deleted file can stay open in a process (covered in earlier chapters). It covers the two systems that manage logs on most modern distributions: logrotate for text files under /var/log, and journald for the systemd journal.
Two log systems, two sets of limits
A typical server writes logs in two ways.
- Text files, such as
/var/log/nginx/access.logor/var/log/syslog. Services orrsyslogappend to them. Nothing limits their size unless something rotates them. - The systemd journal, a binary store written by
systemd-journald. It has its own size limits in its configuration file.
Many servers use both at once. journald collects service output, and rsyslog may also forward the same messages into /var/log/syslog or /var/log/messages. That duplicates data on disk, so check both when a filesystem fills.
How logrotate works
logrotate renames the current log file, starts a fresh one, and removes the oldest copies after a set number of rotations. On most distributions it runs once a day, started by a systemd timer (logrotate.timer) or by a script in /etc/cron.daily.
A rotation with rotate 4 and weekly looks like this over time:
app.logis the live file.- After one cycle,
app.logbecomesapp.log.1, and a new emptyapp.logis created. - After the next cycle,
app.log.1becomesapp.log.2, and so on. - Once the count passes
rotate 4, the oldest file is deleted.
The main configuration is /etc/logrotate.conf. It includes per-service files from /etc/logrotate.d/. Packages install their own files there, so you rarely edit the main file.
A working configuration
This example rotates logs for an application that writes to /var/log/myapp/.
sudo tee /etc/logrotate.d/myapp > /dev/null <<'EOF'
/var/log/myapp/*.log {
daily
rotate 14
maxsize 200M
compress
delaycompress
missingok
notifempty
create 0640 myapp adm
sharedscripts
postrotate
systemctl kill -s HUP myapp.service
endscript
}
EOFThe directives do the following.
| Directive | Effect |
|---|---|
| `daily` | Rotate once per day. `weekly` and `monthly` also exist. |
| `rotate 14` | Keep 14 old files, then delete the oldest. |
| `maxsize 200M` | Rotate early if a file passes 200 MB, even before the next scheduled cycle. |
| `compress` | Compress rotated files with gzip. |
| `delaycompress` | Leave the newest rotated file uncompressed until the next cycle. This protects programs that still write to the old file after rotation. |
| `missingok` | Do not report an error if the log file does not exist. |
| `notifempty` | Skip rotation when the file is empty. |
| `create 0640 myapp adm` | Create the new file with this mode, owner, and group. |
| `sharedscripts` | Run the `postrotate` script once for all matching files, not once per file. |
| `postrotate` | Run a command after rotation, usually to tell the service to reopen its log file. |
Why the postrotate step matters
A process that writes to a log keeps the file open by its inode, not by its name. When logrotate renames app.log to app.log.1, the process keeps writing into the renamed file. The new empty app.log stays unused.
If you then delete the old file, the process still holds it open. This is the situation from the previous chapter on deleted but open files: df shows the space as used, and du cannot see it. The postrotate command avoids this by telling the service to close and reopen its log file. Many services do this when they receive the HUP signal, but check the service's documentation, because some use a different signal or a reload command.
The alternative is copytruncate. It copies the live file and then empties the original in place, so the service never needs to reopen anything.
Testing a configuration safely
Never wait for the nightly run to find out whether a configuration works. Use these two modes.
sudo logrotate -d /etc/logrotate.d/myapp
sudo logrotate -f /etc/logrotate.d/myappThe first command is a debug run. It prints what logrotate would do and changes nothing. The second forces a rotation now, even if the schedule says it is not due. Run the debug mode first and read the output for errors such as wrong permissions or a bad path.
logrotate records when it last rotated each file in a state file, usually /var/lib/logrotate/status (or /var/lib/logrotate.status on some systems). If a rotation seems to be skipped, check this file for the last rotation date.
Common logrotate problems
- The log never shrinks after rotation. The service still writes to the old file because it did not reopen its log. Check for
postrotateand look for a deleted-but-open file withsudo lsof -nP +L1. - Rotation does not happen.
maxsizeandsizeare only checked whenlogrotateruns. If it runs once a day, a file can grow far past the limit between runs. - Permission errors on rotation. On some systems
logrotaterefuses to rotate files in a directory that is writable by a group or others. The error mentions "insecure permissions". Fix the directory permissions, or add asu user groupline to the configuration. - A new file has the wrong owner. Set
createwith the correct mode, owner, and group.
Limiting the systemd journal
The journal can be stored in memory only (/run/log/journal) or on disk (/var/log/journal). Whether it is persistent depends on the Storage= setting. With the default Storage=auto, the journal is persistent only if the directory /var/log/journal exists. When it is persistent, it grows until it reaches its limits.
Checking and trimming current use
Start by measuring.
journalctl --disk-usage
sudo journalctl --vacuum-size=500MThe first command reports how much disk the journal uses. The second removes the oldest archived journal files until the total is about 500 MB. Vacuuming only deletes archived files, not the file currently being written, so the result can end up above the target.
You can also vacuum by age or by file count.
sudo journalctl --vacuum-time=2weeks
sudo journalctl --vacuum-files=10These are one-time actions. They do not stop the journal from growing again.
Setting permanent limits
Permanent limits go in /etc/systemd/journald.conf, or better, in a drop-in file so that package upgrades do not overwrite your changes.
sudo mkdir -p /etc/systemd/journald.conf.d
sudo tee /etc/systemd/journald.conf.d/size.conf > /dev/null <<'EOF'
[Journal]
SystemMaxUse=500M
SystemKeepFree=1G
SystemMaxFileSize=50M
MaxRetentionSec=1month
EOF
sudo systemctl restart systemd-journald| Setting | Meaning |
|---|---|
| `SystemMaxUse=` | Upper limit on total journal size on disk. |
| `SystemKeepFree=` | Journal stops growing when free space on the filesystem would fall below this value. |
| `SystemMaxFileSize=` | Size at which an individual journal file is closed and a new one started. |
| `MaxRetentionSec=` | Maximum age of entries. Older entries are removed. |
| `RuntimeMaxUse=` | The same idea as `SystemMaxUse=`, but for the in-memory journal under `/run`. |
If you do not set SystemMaxUse=, journald defaults to 10 percent of the filesystem size, capped at 4 GB. On a small root filesystem that can still be a large share. The effective limit is the smaller of the size limit and what SystemKeepFree= allows.
After changing the settings, confirm them with journalctl --disk-usage and check the journal's own startup messages with journalctl -u systemd-journald.
Journal files and the df/du gap
Journal files are ordinary files, so du -xh /var/log/journal shows their size. If you vacuum and df does not change, another process may have the old journal files open. Use sudo lsof -nP +L1 to check. Restarting systemd-journald normally releases them.
A routine for a log-filled disk
When a filesystem is nearly full and you suspect logs, work in this order.
- Run
df -hTto confirm which filesystem is full. - Run
sudo du -xh --max-depth=1 /var | sort -h | tail -n 10to see whether/var/logis the cause. - Inside
/var/log, repeat theducommand to find the largest directory or file. - If one file is huge and rotated copies are missing, check its
logrotateconfiguration withlogrotate -d. - Run
journalctl --disk-usageto see if the journal is the cause. - If you must free space immediately and the service holds the file open, truncate it rather than delete it, for example
sudo truncate -s 0 /var/log/myapp/app.log. This frees the blocks at once and keeps the file open for the service. - Fix the cause, either a missing rotation rule or a missing journal limit, so the problem does not return.
Exercise
A web server's /var/log/nginx/access.log was rotated last night. This morning df still shows the filesystem at 95 percent, du shows /var/log/nginx is small, and sudo lsof -nP +L1 lists a deleted access.log.1 held open by nginx. What went wrong, and how do you fix both the immediate problem and the cause?
Show answer
The rotated file was deleted (or renamed and then removed) while nginx still had it open, because nginx was never told to reopen its log file. The space stays allocated until nginx closes the file. Immediately, tell nginx to reopen its logs, for example with sudo systemctl kill -s USR1 nginx.service (or sudo nginx -s reopen), or restart the service if that is acceptable. The blocks are then released and df drops. For the cause, add a postrotate block to the logrotate configuration that sends the reopen signal, then test it with sudo logrotate -d and sudo logrotate -f.
Exercise
Your server's journal uses 3.8 GB on a 20 GB root filesystem. Write the commands to reduce it to about 500 MB now, and the configuration to keep it from growing past 500 MB again.
Show answer
Run sudo journalctl --vacuum-size=500M to trim archived files now. For the permanent limit, create /etc/systemd/journald.conf.d/size.conf containing [Journal] and SystemMaxUse=500M, then run sudo systemctl restart systemd-journald. Confirm with journalctl --disk-usage.