Logrotate & Unicorn for Rails applications

Logrotate is a convenient sysadmin tool to keep log folders tidy and neat. Here is how to use logrotate for log files from Unicorn-served Rails applications.

Let us assume the Rails application is available in /path/to/railsapp and is owned by the user www-data.

In /etc/logrotate.d/railsapp, add:

/path/to/railsapp/log/production.log
/path/to/railsapp/log/development.log
/path/to/railsapp/log/unicorn.stderr.log
/path/to/railsapp/log/unicorn.stdout.log {
        weekly
        missingok
        rotate 8
        compress
        notifempty
        create 640 www-data www-data
        sharedscripts
        postrotate
                kill -s USR2 `cat /path/to/railsapp/tmp/pids/unicorn.pid`
        endscript
}

We can test the configuration with:

logrotate -vf /etc/logrotate.d/railsapp

The postrotate script is important to make sure the new logs are written in the new log file. It is a "sharedscript" as it should only be run once after all log rotations.