logrotate
logrotate is a Linux utility that rotates, compresses and removes log files so they do not fill the disk. It is usually run once a day by a systemd timer or cron job and reads /etc/logrotate.conf plus the per-package rules in /etc/logrotate.d/.
1A typical rule
A rule names one or more log files and directives such as daily or weekly (how often), rotate 7 (how many old files to keep), compress (gzip old files), missingok (no error if the file is absent), notifempty (skip empty logs) and postrotate ... endscript (a command to run after rotation, for example to reopen the log).
2copytruncate
Some programs keep writing to the same open file. copytruncate copies the log and then truncates the original instead of moving it, so the program keeps its file handle; a few lines written during the copy can be lost.
3Testing
logrotate -d /etc/logrotate.conf runs in debug mode and only prints what would happen. -f forces a rotation even if it is not due.
How to add and test a rule
- Create
/etc/logrotate.d/myappwith the log path and directives, for example weekly, rotate 4, compress, missingok, notifempty. - Dry run:
sudo logrotate -d /etc/logrotate.d/myapp - If the output looks right, force one rotation:
sudo logrotate -f /etc/logrotate.d/myapp - Check the result: ls -l the log directory.
Cautions
- A wrong path pattern can rotate or delete logs of other programs.
- Logs managed by the systemd journal are limited in journald.conf, not by logrotate.
Related articles
- journalctl and the systemd journalHow to read logs with journalctl, check how much space the journal uses and shrink it safely with --vacuum options.
- Disk usage with du and ncduHow to find what fills a Linux disk with du and the interactive ncdu, with options that stay on one file system.
- cron and crontabHow cron runs scheduled jobs, the five crontab time fields, where system cron files live and how systemd timers compare.
Sources
- logrotate(8) man7.org
- logrotate(8) (Debian) manpages.debian.org
Last reviewed: