Linux Labs

Packages, services, and logs / Stage 12 of 13

Log rotation and retention

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 9 · theory · 6 min

How rotation works

Rotation renames the log and starts a new one. The rule says when to do it and what to do with the old files.

During rotation logrotate renames app.log to app.log.1, the previous app.log.1 to app.log.2 and so on, and deletes the surplus old ones. Then it creates a new empty app.log, and the program writes to that. The rule from the exercise:

text
/var/log/lab-rotate/app.log {
    size 1k
    rotate 2
    missingok
    notifempty
    nocompress
    create 0640 student student
}

size 1k means rotate once the file is over a kilobyte. rotate 2 keeps two old files. missingok does not treat a missing log as an error, notifempty does not rotate an empty log. nocompress leaves old files uncompressed. create sets the mode, owner and group of the new log.

System rules live in /etc/logrotate.d/. Once a day the logrotate.service runs them on the logrotate.timer, and a condition like size is checked at exactly that moment. logrotate remembers what it rotated and when in a state file: for the system rules it is /var/lib/logrotate/status, for the lesson's rule its own /srv/rotate-lab/state. The --force option rotates the log right away, without checking conditions.

Check yourself 1 question

A log with a size 1k rule in /etc/logrotate.d went over the threshold at 10:00. When will it be rotated?

  • logrotate does not watch files: it checks the size condition when it is run. systemctl list-timers logrotate.timer shows when that is.

  • --force rotates at once and unconditionally, but rotation happens without it too: the timer runs logrotate, which sees the log is over 1k.

logrotate.timer runs the system rules once a day, and size is checked at that moment. Until the run the log can grow far past the threshold.

Key points

  • Rotation renames the log to .1, shifts the old ones and creates a new file.
  • The rule sets the condition, the number of old files, compression and the new log's owner.
  • logrotate.timer runs the system rules once a day; --force rotates at once.
Ubuntu 24.04
Loading…