Adsense Leaderboard Ad

11.05.2012

Rotating Custom Logs with Logrotate on Red Hat

Question sent in by Stacy from Magnolia:

Q: I have a RHEL 6 system and run several custom scripts that generate semi-large log files. What is the easiest way to rotate these logs? I was thinking about writing a script to rotate the logs, but I would have to write a different log rotate script for every log file I have.

A: Well no need to write you own script since there is already a utility built for exactly what you need. Logrotate or logrotated is a daemon that runs on most modern linux systems and rotates the system logs. You will notice this on RHEL in the /var/log directory the messages, maillog and other are all rotated out weekly by default.

So here is a simple way to rotate your custom log files. One edit of a file and your done. For this example we will use a log file name of /var/log/custom.log. We will open the /etc/logrotate.d/syslog file in your favorite text editor, I use vim. NOTE: This must be done as root or using sudo to elevate your privileges.

Here is an example file:

/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
endscript
}
Just add your custom log file to the list of files that syslog already rotates like so: /var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
/var/log/yum_out.log
/var/log/custom.log
{
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
endscript
}
Save the file and your done. Now your custom.log file will be rotated using the default settings for syslog.

If you would like to know what the default settings are, or if you would like to change them you can view or edit the /etc/logrotate.conf file.

The default settings in Red Hat, CentOS and Fedora are:
Rotate log files weekly
Keep 4 Weeks worth of backlogs
Create a new empty log file after rotating old ones
Use date as suffix of rotated file
DO NOT compress log files

If you require different settings than the default for a specific log file you can override the default settings by creating a new file in the /etc/logrotate.d/ directory with your new settings. For example, let's say we wanted to rotate the custom.log file daily instead of the default weekly and save 7 rotated logs. We can create a file called /etc/logrotate.d/customlog with the following contents.

/var/log/custom.log
{
daily
rotate 7
}



Logrotate is a powerful tool for administrators with many options. It would be impossible to cover all of them in this article. For more information about the different options please read the man pages.
LOGROTATE MAN PAGE

I hope this answers your question. Please feel free to comment below.

No comments:

Post a Comment