logrotate [man page] - rotates, compresses, and mails system logs
logrotate [-dv] [--force] [-s|--state statefile] config_file ..
logrotate is a handy tool for system administrators who wish to take the /var/log directory under their control. The logrotate command is called daily by the cron scheduler and it reads the following files:
Let's say that we are running a service called "linuxserver" that is creating logfiles called "linux.log" within the /var/log/linuxserver directory. To include "linuxserver" log files in the log rotation we need to first create a logrotate configuration file and then copy it into the /etc/logrotate.d directory.
create 660 linuxuser linuxuser }
This config file will run daily, create maximum 7 archives owned by linuxuser and linuxuser group with 660 permissions, compress all logs and exclude only yesterdays and empty log files. Here are some selected logrotate configuration keywords. For complete guide see [[manpage_logrotate | man page]]:
|daily||Log files are rotated every day.|
|weekly||Log files are rotated if the current weekday is less than the weekday of the last rotation or if more than a week has passed since the last rotation. This is normally the same as rotating logs on the first day of the week, but if logrotate is not being run every night a log rotation will happen at the first valid opportunity.|
|monthly||Log files are rotated the first time logrotate is run in a month (this is normally on the first day of the month).|
|notifempty||Do not rotate the log if it is empty (this overrides the ifempty option).|
|nocompress||Old versions of log files are not compressed.|
|delaycompress||Postpone compression of the previous log file to the next rotation cycle. This only has effect when used in combination with compress. It can be used when some program cannot be told to close its logfile and thus might continue writing to the previous log file for some time.|
|compress||Old versions of log files are compressed with gzip by default.|
|mail address||When a log is rotated out of existence, it is mailed to address. If no mail should be generated by a particular log, the nomail directive may be used.|
|missingok||If the log file is missing, go on to the next one without issuing an error message.|
Once config file is ready just simply copy it into logrotate directory and change owner and permissions:
cp linuxserver /etc/logrotate.d/
chmod 644 /etc/logrotate.d/linuxserver
chown root.root /etc/logrotate.d/linuxserver
Finally, you can experiment with the log rotation (outside of the usual cron job) by forcing an execution of the logrotate in the absence of any log files to rotate.
logrotate -f /etc/logrotate.d/linuxserver