Log rotation in Linux

This thing bugged me a lot. In general all applications create logs and depending on how much information is passed on to the log file, log file might end up taking gigs of space (as it happened in my case). So I searched for a solution and got one. It is ‘logrotate’. Using logrotate on linux lets you configure the rotation of log files. It can create new log files, remove old ones after compressing them. This can be done on daily or monthly basis or you can even customize it as per your need.

Lets say you have a log file @ this location:

/usr/local/log/file_to_rotate.log

You can rotate this file using a simple configuration file which should look like this:

# Your logs:
/usr/local/log/file_to_rotate.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
}


This will compress the log file and max 14 compressed, rolled over files will be created (one per day so total 14 in 2 weeks). After that older rolled over files will be deleted. So at a given time, only 14 rolled over files would exist on the file system. You might be required to restart the server in some cases. Auto restart can be done with the following addition in the above written configuration script:

/usr/local/log/file_to_rotate.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
postrotate
/etc/init.d/myserver restart
endscript
}

postrotate…endscript block lets you specify things you need to do after rotating the log. With this script in place @ this location:

/user/conf_folder/rotation.conf

Lets add this in cron tasks. You need to do this for adding a new cron job:

$ crontab -e

Add the following code in the file:

00 00 * * * /usr/sbin/logrotate -s /home/user/config/logrotate.status /user/conf_folder/rotation.conf

Cron will take care of executing logrotate @ midnight everyday. Out of the three arguements, first one is the place where logrotate resides, second one following -s arguement is the one where logrotate will be keeping its status file and the last one is the configuration file you made in the first step.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s