Rotating your log files with logrotate

Posted on November 2, 2010

If you’re like me and you’re used to log what’s going on your web application, you might want to know how to rotate your log files just like Linux commonly does for its system logs. No need to code anything for that purpose, you can simply use the same software as your system: logrotate.

Attention: I wrote this post based on my personal server which is a Linux Debian 5.0 Lenny and logrotate 3.7.1, but it’s very likely that it works more or less the same way for any Linux server and version of logrotate.

When installing logrotate, it’s likely that it’s already designed to rotate some system logs (syslog, kern.log …), and in the case of a web server, it also rotates Apache or MySQL (access.log, error.log, mysql.log…). Having a quick look at the manual (#man logrotate), you’ll see you can easily tell logrotate to handle your own log files. Simply open /etc/logrotate.conf (or touch a new file in /etc/logrotate.d/ if it exists for your version), and add something like the following:
"/home/mysite/log/visitors.log" "/home/mysite/log/downloads.log" {
rotate 5
size 100k
/usr/bin/killall -HUP httpd

This example section will handle both visitors.log and downloads.log (you can add as many file locations as you wish). The options are:
  • rotate 5: it means it will rotate 5 times before deleting data
  • mail will send an email with the content of the latest log file before deleting it
  • size 100k: maximum size for a log file before rotating it
  • postrotate […] endscript: enclosed is a piece of script you want to be run after rotating logs
  • nocompress: add this line to prevent logrotate from compressing rotated log files

These are the main options for logrotate, but of course many others can be found, please read the manual for more.

And there you are, your custom log files are being rotated without having to code a custom PHP script 🙂

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.

Leave the first comment