Setting Up Log Rotation with logrotate
Without log rotation, log files grow indefinitely and can fill your disk. logrotate automatically archives and deletes old logs.
How logrotate Works
logrotate is typically run daily by cron. It reads config files in /etc/logrotate.d/ and rotates matching log files based on your rules.
View Existing Configs
ls /etc/logrotate.d/
cat /etc/logrotate.d/nginx
Create a Custom Config
nano /etc/logrotate.d/myapp
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
Key Directives Explained
daily/weekly/monthly— rotation frequencyrotate 7— keep 7 rotated files before deletingcompress— gzip old log filesdelaycompress— compress previous rotation, not the current one (helps apps still writing)missingok— do not error if the log file is missingnotifempty— do not rotate empty log filespostrotate— command to run after rotation (e.g., send HUP to reopen log files)
Test Your Config
logrotate -d /etc/logrotate.d/myapp
The -d flag runs in debug/dry-run mode — shows what would happen without actually rotating.
Force a Rotation Now
logrotate -f /etc/logrotate.d/myapp