Operation Systems

Setup Logrotate on Linux

Most Linux systems will come with am installed tool, logrotate, that rotates log files. Unless rotated, log files keep growing until they fill all the free space . Rotating them means copying them to a backup file and creating a new empty log. Backup logs are usually removed when they are to far out of date. Usually logrotate runs without any special configuration by the system administrator. Most of the times it is installed to run nightly as a cron job and each service you install, as a separate package, will also install a custom configuration file that tells logrotate how to rotate the log files for that application.
What most users never realize is that they can make use of logrotate as well. If you have any programs that keep a log then logrotate will save you some time by cleaning up for you. Logrotate can easily be used by normal users and the super user.

In this example I’ll show how to set logrotate for Apache webserver logs. By default the custom logrotate configuration files are saved in this directory /etc/logrotate.d/.

We will create a file called /etc/logrotate.d/httpd. Below is the configuration file that i have set in logrotate for this service. Next paragraph i will explain in details each logrotate directive I have used.

###########################
/var/log/httpd/*log {
weekly
rotate 5
copytruncate
# compress
missingok
notifempty
# sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/httpd.pid 2>/dev/null` 2> /dev/null || true
endscript
}
###########################

# That is where my logs are being saved.
/var/log/httpd/*log {

# rotate log files weekly
weekly

# rotates keeps logs for 5 weeks then overwrites.
rotate 5

# tells logrotate not to rotate a log if it’s already empty
notifempty

# tells logrotate not to issue an error if the log file is missing
missingok

# The rotating scripts are only run once, no matter how many logs match the wildcarded pattern.
sharedscripts

# contains a block of instructions on what logrotate should do after the logs have been rotated. In our case we kill apache server so we can make it work with the new log files.
postrotate
/bin/kill -HUP `cat /var/run/httpd.pid 2>/dev/null` 2> /dev/null || true
endscript
}

Additional useful parameters:

copytruncate – copytruncate tells logrotate to copy and truncate the original log file in place instead of renaming it and creating a new logfile. Some programs work better with this behavior

compress – tells logrotate to compress old logs when they are rotated

Leave a Reply