/etc/logrotate.d/apache2.conf
/var/log/apache2/* {
weekly
rotate 3
size 10M
compress
delaycompress
}
The first line indicates that the directives inside the block apply to all logs inside /var/log/apache2:
- weekly means that the tool will attempt to rotate the logs on a weekly basis. Other possible values are daily and monthly.
- rotate 3 indicates that only 3 rotated logs should be kept. Thus, the oldest file will be removed on the fourth subsequent run.
- size=10M sets the minimum size for the rotation to take place to 10M. In other words, each log will not be rotated until it reaches 10MB.
- compress and delaycompress are used to tell that all rotated logs, with the exception of the most recent one, should be compressed.
Let’s execute a dry-run to see what logrotate would do if it was actually executed now. Use the -d option followed by the configuration file (you can actually run logrotate by omitting this option):
/var/log/squid/access.log {
monthly
create 0644 root root
rotate 5
size=1M
dateext
dateformat -%d%m%Y
notifempty
mail gabriel@mydomain.com
}
- Instead of compressing the logs, we could rename them after the date when they were rotated. To do that, we will use the dateext directive. If our date format is other than the default yyyymmdd, we can specify it using dateformat.
- Note that we can even prevent the rotation from happening if the log is empty with notifempty.
- In addition, let’s tell logrotate to mail the rotated log to the system administrator.
- As we see, this log did not need to be rotated. However, when the size condition is met (size=1M) , The rotated log will be renamed access.log-25082016 (if the log was rotated on August 25, 2016) and the main log (access.log) will be re-created with access permissions set to 0644 and with root as owner and group owner.
- Finally, when the number of logs finally reaches 6, the oldest log will be mailed to webnoid@domain.com.
- Now let’s suppose you want to run a custom command when the rotation takes place. To do that, place the line with such command between the postrotate and endscript directives.
/var/log/myservice/* {
monthly
create 0644 root root
rotate 5
size=1M
postrotate
echo “A rotation just took place.” | mail root
endscript
}
compress : This is used to compress the rotated log file with gzip.
Delaycompress : When used with the compress option, the rotated log file is not compressed until the next time it is cycled.
Prerotate/endscript These are statements that enclose commands to be executed prior to a log file being rotated. The Prerotate and endscript keywords must appear on a line by themselves.
Postrotate/endscript : These are statements that enclose commands to be executed after a log file has been rotated. The Postrotate and endscript keywords must appear on a line by themselves.