Where to start First steps track · 15 stages
Linux Labs

Log rotation with logrotate

cheat sheet · Ubuntu 24.04 https://lab.dimsanych.ru/en/wiki/logrotate/

Cheat sheet

  • sudo logrotate -d /etc/logrotate.conf dry run (changes nothing)
  • sudo logrotate -f /etc/logrotate.d/nginx force it now
  • cat /var/lib/logrotate/status rotation history

Configuration

Globally in /etc/logrotate.conf, per service in /etc/logrotate.d/<service>:

/var/log/myapp/*.log {
    daily                 # how often (daily/weekly/monthly) — or size 100M
    rotate 14             # keep 14 copies
    compress              # compress old ones (.gz)
    delaycompress         # don't compress the most recent rotated file (still being appended to)
    missingok             # fine if the log is missing
    notifempty            # don't rotate empty files
    dateext               # date suffix (file-20260101) instead of .1
    create 0640 myapp myapp   # create a new log with these permissions/owner
    su myapp myapp            # run as this user (if the directory isn't root's)
    sharedscripts             # run postrotate once for all files in the pattern
    postrotate
        systemctl reload myapp >/dev/null 2>&1 || true
    endscript
}

Directives

Directive Meaning
daily/weekly/monthly the period
size 100M rotate by size (instead of, or together with, the period)
rotate N how many copies to keep
compress/delaycompress compress / defer compression by one cycle
copytruncate copy and truncate (if the service can't reopen its log file)
postrotate…endscript a command to run after rotation (reload the service)
maxage N delete files older than N days

postrotate (reload/reopen) or copytruncate is required for the service to start writing to the new file.

Loading…