How to remove old log files with Logrotate

Configure the Logrotate maxage directive to automatically delete rotated log files older than a specified number of days.

Configure Logrotate to automatically delete rotated log files that exceed a specified age in days.

Prerequisites

  • Linux system with Logrotate installed.
  • Root or sudo access to edit files in /etc/logrotate.d/.
  • An existing Logrotate configuration file for the target application.

Step-by-Step: Remove Old Log Files with Logrotate

  1. Open the Logrotate configuration file for the target application. This example uses Nginx:

    sudo nano /etc/logrotate.d/nginx
  2. Add the maxage directive inside the log file block. Logrotate deletes rotated files older than the specified number of days:

    /var/log/nginx/*.log {
        daily
        rotate 14
        compress
        maxage 30
        missingok
        notifempty
    }

    Logrotate interprets maxage 30 as 30 days. It checks each rotated file's last modification timestamp and deletes files that exceed the threshold.

    Logrotate configuration with maxage parameter at 30 days

    Common maxage values:

    Retention Periodmaxage Value
    24 hoursmaxage 1
    7 daysmaxage 7
    30 daysmaxage 30
    6 monthsmaxage 182
    1 yearmaxage 365
  3. Save the configuration file and exit the editor.

  4. Test the updated Logrotate configuration in debug mode to verify the maxage directive works:

    sudo logrotate -d /etc/logrotate.d/nginx

    Logrotate prints the actions it would take without modifying any files. Look for lines indicating files that would be removed due to age.

How to Verify Old Log Files Are Removed

Logrotate applies the maxage directive on its next scheduled run. After one full rotation cycle, check the log directory for old files:

ls -la /var/log/nginx/

Rotated files older than the maxage threshold should no longer exist.

Common Issues When Removing Old Log Files with Logrotate

Log files persist beyond the maxage threshold.Logrotate only deletes files it manages. Manually created or renamed log files outside Logrotate's rotation naming pattern are not affected by maxage.

The maxage and rotate directives conflict.The rotate directive limits the number of retained copies. The maxage directive limits retention by age. Logrotate applies both rules. A file is removed if it exceeds either threshold.

Logrotate does not run on schedule.The maxage directive takes effect only when Logrotate runs. If the daily cron job is missing or disabled, old files accumulate. Verify the cron job exists at /etc/cron.daily/logrotate.

For a full reference of all Logrotate directives, see the Logrotate directives reference.