1. Home
  2. Hosting & Servers
  3. Web Hosting
  4. How to Setup and Manage Log Rotation Using Logrotate in Linux
  1. Home
  2. Hosting & Servers
  3. Web Hosting
  4. How to Setup and Manage Log Rotation Using Logrotate in Linux

How to Setup and Manage Log Rotation Using Logrotate in Linux

In RHEL/CentOS and Fedora

# ls /var/log

In Debian and Ubuntu

# ls /var/log

Installing Logrotate in Linux

On Debian and Ubuntu :-

# aptitude update && aptitude install logrotate

On CentOS, RHEL and Fedora :-

# yum update && yum install logrotate

include /etc/logrotate.d

To insert the following contents in /etc/logrotate.d/apache2.conf

Note that most likely you have to create that file) and check each line to indicate its purpose:

/var/log/apache2/* {
    weekly
    rotate 3
    size 10M
    compress
    delaycompress
}

First line indicates that the directives inside the block apply to all logs inside /var/log/apache2 :

  • weekly >> means that the tool will attempt to rotate the logs on a weekly basis. Other possible values are daily and monthly.
  • rotate 3 indicates that only 3 rotated logs should be kept. Thus, the oldest file will be removed on the fourth subsequent run.
  • size=10M sets the minimum size
  • compress and delaycompress are used to tell that all rotated logs, with the exception of the most recent one, should be compressed.

# logrotate -d /etc/logrotate.d/apache2.conf

This time we will use /etc/logrotate.d/squid.conf to only rotate /var/log/squid/access.log:

/var/log/squid/access.log {
monthly
create 0644 root root
rotate 5
size=1M
dateext
dateformat -%d%m%Y
notifempty
mail [email protected]
}

For example, suppose we want to send an email to root when any of the logs inside /var/log/myservice gets rotated.

Let’s add the lines in red to /etc/logrotate.d/squid.conf:

/var/log/myservice/* {
monthly
create 0644 root root
rotate 5
size=1M
postrotate
echo “A rotation just took place.” | mail root
endscript
}

it is important to note that options present in /etc/logrotate.d/*.conf override those in the main configuration file in case of conflicts.

Logrotate and Cron

By default, the installation of logrotate creates a crontab file inside /etc/cron.daily named logrotate. As it is the case with the other crontab files inside this directory, it will be executed daily starting at 6:25 am if anacron is not installed.

Otherwise, the execution will begin around 7:35 am. To verify, watch for the line containing cron.daily in either /etc/crontab or /etc/anacrontab.

 

 

 

 

 

 

 

 

 

 

 

 

Updated on April 21, 2020

Was this article helpful?