How to remove old log files using Logrotate

Remove old log files using Logrotate (older than 30 days, 24 hours, 6 months etc.)

Using Logrotate, you can remove older log files such as removing logs older than 24 hours, 7 days, 6 months and so on. You can set your own schedule how to remove old logs.

Follow these instructions. In our example below, we're using Nginx log files:

  1. Edit the logrotate configuration file:

     $ nano /etc/logrotate.d/nginx
  2. Add a new directive with the maxage parameter that sets the maximum number of days the log is available until it's deleted:

     /var/log/nginx/*.log {
        ...
        maxage 30
        ...
     }

    30 is the number of days, i.e. 30 days.

    Logrotate configuration with maxage parameter at 30 days

    To remove log files after 24 hours, simply change 30 to 1 (1 day, 24 hours):

     /var/log/nginx/*.log {
        ...
        maxage 1
        ...
     }

    To delete the log files after 6 months, use 182 value for the maxage parameter (182 days is 6 months):

     /var/log/nginx/*.log {
        ...
        maxage 182
        ...
     }
  3. Save the /etc/logrotate.d/nginx file changes.