Log Files & logrotate
The journal rotates itself, but plenty of logs are still plain files: Nginx access and error logs, /var/log/auth.log written by rsyslog, application logs in /var/log/<app>/. A file that only ever grows fills the disk eventually; the classic 3 a.m. outage is "/var is 100% full because of access.log". logrotate prevents that. A systemd timer (logrotate.timer, daily) runs it with /etc/logrotate.conf, which includes every file in /etc/logrotate.d/.
A config, line by line
/var/log/inventory/*.log {
daily # or weekly, monthly, or size-based (below)
rotate 14 # keep 14 old files, delete older ones
compress # gzip rotated files...
delaycompress # ...but not the newest one (a process may still write to it)
missingok # no error if no file matches
notifempty # don't rotate an empty file
create 0640 inventory adm # make a new empty file with this mode and owner
sharedscripts # run postrotate once for all matching files, not once per file
postrotate
systemctl kill -s HUP inventory.service
endscript
}The important design question is how the app learns about the new file. A process writes to an open file descriptor, not to a name: after logrotate renames app.log to app.log.1, the app happily keeps writing into app.log.1. Three ways out:
| Strategy | How | Trade-off |
|---|---|---|
create + signal |
rename, create a new file, postrotate tells the app to reopen (Nginx: USR1, many daemons: HUP) |
clean; the app must support reopening |
copytruncate |
copy the file, then truncate the original in place | works with any app; lines written between copy and truncate are lost |
| let the app rotate | the app (or its logging library) rotates by itself | then logrotate must not touch those files |
Seeing what logrotate would do
logrotate -d is a dry run that prints its decisions. With -s the state file (when each log was last rotated) lives in the working directory instead of /var/lib/logrotate/status, and -f forces a rotation regardless of the schedule:
mkdir -p logs && seq 1 1000 > logs/app.log && : > logs/empty.log
cat > rotate.conf <<'EOF'
/home/learner/logs/*.log {
daily
rotate 3
compress
delaycompress
missingok
notifempty
create 0640
}
EOF
logrotate -d -f -s state rotate.conf 2>&1 | grep -v -e '^warning' -e '^