Wednesday, August 31, 2011

File Backups with logrotate

Logrotate is a log rotating program, that usually gets executed daily by a cron job. It has a main configuration file located at "/etc/logrotate.conf" and additional configs are usually store in the directory located at "/etc/lofrotate.d". The options in the configuration file are dead simple to understand and can be learned from its manpage (man logrotate). Logrotate is mainly used to backup and rotate log files but can be used on any file.
The following example will show how to back up contents of the /var/www folder.

First thing we will do is create a directory to house our configuration file and the backups. We will do this in our home directory at "/home/user".

# mkdir backups
# cd /home/user/backups

We then create the config file named rotate.conf:

### logrotate config file
/home/user/backups/www.tar{
rotate 4
daily
compress
copy
prerotate
rm /home/user/backups/www.tar
tar -cf /home/user/backups/www.tar /var/www
endscript
}
###


A quick run down of the config options:
-The first line gives the path to the file we want to backup and rotate
-Rotate 4 will keep up to 4 backups and rotate onwards
-daily is set to have log files rotated daily
-Compress will use gzip to compress the file by default
-copy just makes a copy of the original file for backup
-The prerotate directive allows us to run commands before rotating the logs. The commands i used should be straight forward enough to understand, but anything can go here. You must end the prerotate directive with endscript.

In our setup, logrotate will need a dummy file called www.tar to start off properly, so we will create an empty file with that name:

# touch www.tar

Thats it for the configuration. Now to run logrotate issue the following:

# logrotate -f /home/user/rotate.conf

the "-f" option tells logrotate to force the rotation.

Running this command a few times (7-8) will basically cause several backups to be created and rotated as need be. You would eventually notice that only 4 backups are being kept as per our configuration.

Resouces/Good Reading:
kangaroobox.blogspot
manpage
thegeekstuff.com

No comments:

Post a Comment