How to enable log rotation on Linux hosts

Log rotation is an way to manage old log files to reduce disk space usage on the server.logrotation

By default log rotate is invoked once a day using a cron scheduler from location /etc/cron.daily/

grep logrotate.conf /etc/cron.daily/logrotate
/usr/sbin/logrotate /etc/logrotate.conf >/dev/null 2>&1

Log rotation is manged by two different configuration files /etc/logrotate.conf [generic file] and a service specific configuration file placed under /etc/logrotate.d/ folder.

For example, we have to add below contents in /etc/logrotate.d/cmdlog (name can be anything) file to enable log rotation for /var/log/cmdlog.log.

/var/log/cmdlog.log
{
missingok
notifempty
size 200M
rotate 5
compress
create 0600 root root
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
endscript
}

Where,

/var/log/cmdlog.log : Log file for which rotation is needed; We can specify multiple log files[one per line] or else use regex to cover multiple log files. Example : /var/log/*.log can be used.

missingok : Do not output error if log file is missing.

notifempty : Do not rotate log file if it is empty

size : Log file is rotated only if it grow bigger than the specified size.

rotate : ensures that logrotate keeps a specified number of backup of log files.

compress : Old versions of log files are compressed with gzip by default.

create : Creates a new log file wit permissions 600 where owner and group is root user.

daily, weekly, monthly, or yearly : Backup rotation interval

prerotate & postrotate : In some cases, we might have to restart a service or kill a process before or after rotating logs in such cases we can use these options.

For more available options, try “man logrotate” command.

Once above file is created, either we can wait for logrotation to happen when the cron runs or else we can issue below command to run logrotate forcefully.

logrotate -f /etc/logrotate.conf