Wednesday 2 December 2015

Rotate custom log files with logrotate

What:

Linux server - Debian, Ubuntu, Red Hat, Centos, SLES

Problem:

Your custom logs are getting out of control, they filling up server drive.

Solution:

Navigate to /etc/logrotate.d/
cd /etc/logrotate.d/

Create a new file with relevant name i.e.
touch my_logs

Edit file and add the following:
vi /etc/logrotate.d/my_logs
/var/log/custom_dir/*.log
{
        rotate 2
        size 100M
        missingok
        notifempty
        compress
        create
}

A word of explanation:

First line is a path to your log directory, yes you can use wildcards.

rotate 2 - log files are rotated 2 times before being removed. If count is 0, old versions are removed rather than rotated
size 100M - log files are rotated only if they grow bigger than 100MB
missisngok - if the log file is missing, go on to the next one without issuing an error message
notifempty - do not rotate the log if it is empty
compress - old versions of log files are compressed with gzip by default
create - immediately after rotation (before the postrotate script is run) the log file is created with the same name, ownership and permissions

Test your config.
logrotate -d /etc/logrotate.d/my_logs

logrotate -d - debug mode, no changes will be made to the logs or to the logrotate state file.

There are plenty of options, so make sure to check man page.

No comments:

Post a Comment