Linux logs can grow uncontrollably, overwhelming disk space and slowing down your system. To prevent this, log rotation ensures old logs are archived or deleted when they reach a certain size or age, while maintaining critical log entries. The simplest solution is to use the built-in logrotate tool, which you can configure with a custom logrotate configuration file. This guide covers how to set up, manage, and troubleshoot log rotation properly.
What You'll Need
- Root or sudo access to your Linux system to modify configuration files.
- A basic understanding of command-line interfaces to manage log rotation settings.
- Existing log files you want to rotate (most common are system logs like
/var/log/syslog,/var/log/auth.log, or application-specific logs). - Optional: A text editor like
nano,vim, orgeditfor editing configuration files.
Step-by-Step How to Configure Log Rotation
Check existing logrotate configuration files
- Navigate to the default logrotate configuration directory:
sudo find /etc/logrotate.d/to locate existing configurations, orsudo find /etc/logrotate.conffor the main configuration file. - Review common logrotate entries, especially for system logs like
syslog,auth.log, or application logs in/var/log/.
- Navigate to the default logrotate configuration directory:
Create or modify a custom logrotate configuration
- Create a new configuration file in
/etc/logrotate.d/, naming it something descriptive likecustom_app_logs.conf. - Use a text editor to open the file, for example:
sudo nano /etc/logrotate.d/custom_app_logs.confand add the following basic template (replace parts in[]with your needs):/var/log/my_app.log { daily missingok rotate 7 compress delaycompress notifempty create 640 myapp myapp sharedscripts postrotate systemctl reload myapp.service endscript }Explanation of key parameters:
daily: Rotate logs daily (other options:weekly,monthly, ornever).rotate 7: Keep 7 copies of each log file.compress: Compress rotated logs (usinggziporxzby default).delaycompress: Wait until a log is empty to compress it.missingok: Ignore missing log files without erroring.notifempty: Skip rotation if the log file is empty.create 640 myapp myapp: Create new log files with the specified permissions and ownership.sharedscripts: Run postrotate commands for all files in this group.postrotate: Execute commands after rotation (e.g., service reload).
- Create a new configuration file in
Test log rotation without triggering it immediately
- Manually simulate rotation using the
logrotatecommand without arguments:sudo logrotate -d /etc/logrotate.d/custom_app_logs.confThis dumps the configuration to stdout for verification. - If the configuration is correct, run the regular logrotate command to see if it generates errors:
sudo logrotate -f /etc/logrotate.d/custom_app_logs.conf-fforces immediate rotation without waiting for the next scheduled run.
- Manually simulate rotation using the
Schedule log rotation with cron
- Check if logrotate is already scheduled:
sudo crontab -lto review the current cron jobs. - If you need to add a cron job, edit your user's crontab:
sudo crontab -eAdd this line to run logrotate daily at 3 AM:30 3 * * * /usr/sbin/logrotate /etc/logrotate.confNotes:
- Use
/etc/logrotate.conffor the main configuration file. - Cron paths in
/usr/sbin/may vary by system (check withwhich logrotate).
- Use
- Check if logrotate is already scheduled:
Verify log rotation is working
- Check logrotate logs for errors:
journalctl -u logrotate(on systems using systemd) ortail -f /var/log/syslog | grep logrotateto monitor its activity. - Monitor your application logs directly to confirm rotation:
tail -f /var/log/my_app.logand check for new rotated logs likemy_app.log.7.gz.
- Check logrotate logs for errors:
Common Mistakes
- Overcomplicating the configuration: Avoid excessive customization. Stick to core parameters like rotation frequency, file retention, and compression unless necessary. Complex settings can cause issues if you forget to update them.
- Missing permissions: Ensure the logrotate configuration file and its directories are readable by root. A missing
createdirective or incorrect permissions can prevent log files from being created after rotation. - Ignoring postrotate commands: If you include
sharedscriptsorpostrotate, ensure these commands execute correctly. Test them manually first to avoid downtime or configuration drift. - Not testing configurations: Always test logrotate with
-dor-fbefore relying on it in production. A misconfigured logrotate can corrupt logs or skip critical entries. - Blocking file access during rotation: Avoid commands that hold file locks (e.g.,
tailorgrepfollowing rotation) during rotation to prevent log files from being overwritten. - Forgetting rotation in critical services: Log rotation should not disrupt services. If your postrotate command reloads a service, ensure it’s idempotent (i.e., it won’t fail if run multiple times).
Tips
Use
logrotate -vfor verbose output to debug issues:sudo logrotate -v /etc/logrotate.d/custom_app_logs.conf- This shows each file processed, compressed, or skipped.
For system-wide logs, consider
/etc/logrotate.d/templates:- Use
/etc/logrotate.d/syslogfor system logs likesyslogorauth.log. - Common templates include
syslog,auth, andkernfor kernel logs.
- Use
Backup critical logs before rotation:
- Use a script to copy logs to a backup location before rotation:
sudo cp /var/log/my_app.log /var/backups/my_app.log.bakbefore running logrotate.
- Use a script to copy logs to a backup location before rotation:
Monitor disk space before enabling logrotate:
- Check free space with
df -hto ensure logs won’t fill up a small partition. - Consider using compressed logs for high-volume applications.
- Check free space with
Use
logrotate --debugfor advanced troubleshooting:- This logs detailed information about file handling, permissions, and compression.
Document your logrotate setup:
- Save a copy of your logrotate configuration in a version-controlled file or comment it in the central config.
Troubleshooting
Logs aren’t rotating as expected
- Check if logrotate is running:
sudo systemctl status logrotateorps aux | grep logrotateto confirm it’s active. - Verify the configuration file is being read:
sudo cat /etc/logrotate.conf | grep -A 10 "custom_app_logs"to see if your file is included. - Test with
-f:sudo logrotate -f /etc/logrotate.d/custom_app_logs.confto force rotation immediately. - Check for permission issues:
ls -la /etc/logrotate.d/custom_app_logs.confand ensure root can read/write. - If logs are stuck, try
logrotate --force:sudo logrotate --force /etc/logrotate.conf
- Check if logrotate is running:
Compression failures
- Ensure the
compressdirective uses a supported tool (e.g.,gzip,xz). - Check if
xzorgzipis installed:which gziporwhich xzto confirm. - If compression fails, remove
compressordelaycompresstemporarily to test. - Manually test compression:
gzip -t my_app.log.7to verify the file can be compressed.
- Ensure the
Postrotate commands failing
- Test postrotate commands manually:
sudo /etc/logrotate.d/custom_app_logs.conf | grep postrotatethen run the commands directly:sudo systemctl reload myapp.serviceto verify. - If the service isn’t loaded, run:
sudo systemctl enable myapp.servicebefore testing. - Check service status:
sudo systemctl status myapp.serviceif the reload fails.
- Test postrotate commands manually:
Logs appear corrupted after rotation
- Verify no file locks are holding up rotation.
- Check for manual log appends during rotation:
tail -f /var/log/my_app.logand stop new writes temporarily. - If the issue persists, rotate logs manually first, then verify the rotated file is intact:
tail -n 50 my_app.log.7to check contents.
Cron job not running logrotate
- Check cron logs:
sudo grep CRON /var/log/syslogorjournalctl -u cronto see if the job executed. - Test the cron path manually:
sudo /usr/sbin/logrotate /etc/logrotate.confto confirm it works. - If the path is incorrect, update the cron line:
30 3 * * * /usr/bin/logrotate /etc/logrotate.conf(replace/usr/sbin/with the actual path).
- Check cron logs:
Logs are still filling disk space
- Increase rotation frequency or reduce retention:
rotate 14(keep 14 days of logs). - Use
notifemptyto skip empty logs if they’re not critical. - Consider splitting logs into multiple files or using log aggregation tools like ELK or Fluentd for archival.
- Check for log growth sources:
du -sh /var/log/*to identify unusually large log directories.
- Increase rotation frequency or reduce retention:
Frequently Asked Questions
How do I set up log rotation for a specific application's logs?
Create a new file in /etc/logrotate.d/, add a template with rotation parameters (e.g., daily, rotate 7, compress), and include the application's log path. For example, for a service named myapp, use:
/var/log/myapp.log {
daily
missingok
rotate 7
compress
notifempty
create 640 myapp myapp
}
What if I don’t want logs compressed?
Remove the compress and delaycompress directives. Logrotate will skip these options when not specified.
How can I manually trigger log rotation?
Use the logrotate command without arguments:
sudo logrotate
To force immediate rotation:
sudo logrotate -f /etc/logrotate.conf
Why aren’t my rotated logs showing up?
Check for permissions, verify the log path in your configuration, and ensure create permissions are set correctly (e.g., create 640 myapp myapp). If the log file doesn’t exist, missingok will prevent logrotate from failing, but no rotation will occur.
Can I rotate logs for multiple services at once?
Yes, use sharedscripts in your logrotate configuration to run postrotate commands for all matching files. For example:
/var/log/*.log {
daily
sharedscripts
postrotate
systemctl reload myapp.service myapp2.service
endscript
}
How do I troubleshoot logrotate not working?
Start with logrotate -v for verbose output. Check cron logs, verify file permissions, and ensure the configuration includes all specified paths. If logs still appear unrotated, test with -f or manually edit the config file.