Rails log-rotate

There has been one thing that most people overlook after deploying their Rails / web app, and that’s log-ration.
I have to admit, it’s something that I overlooked myself for quite some time.

When using capistrano for deployment, your production log gets stored in the share folder, so the same log stays available after updates. But after a while, you log file will get bigger and bigger, until it eats up all available disk space.

The following snippet is the configuration I use for rotating my rails logs and is stored in the /etc/logrotate.d/ directory.

/srv/*/*/current/log/*.log {
  rotate 7
  minsize 1

The line before the opening curly bracket tells logrotate where to look for the log files. All my projects are stored in the /srv directory, followed by a client name and project name. Since those entries are variable, I just wildcard them.
Since I use capistrano, logrotate can access the logs through the current symlink (or you can use the shared folder as well).
As last part, I wildcard the log file names that end with the .log extension. I do that so all logs get rotated, and not only for example the production.log.

daily: this entry tells logrotate to rotate the log files on daily bases.
missingok: makes sure logrotate doesn’t throw any errors when a log file is not found, so it continues to run
rotate X: rotate log files X times, before discarding older logs. When the logs get rotated for X+1, the oldest logs get deleted
minsize X:  defines the minimum size a log file should have before it rotates
compress: compress the log file so you get some extra disk space. Keep in mind that the first rotated log will stay uncompressed ( xxxx.log.1 )
delaycompress: Postpone compression of the previous log file to the next rotation cycle.

The copytruncate is something that you definitely will need if you don’t want to restart your rails app every time you rotate your logs! It makes sure the original log file will get truncated after a copy has been made, instead of moving the old log file and creating a new one.

If you wouldn’t use copytruncate, logrotate would just move your production.log to production.log.1, which would make Rails verry unhappy, since it wouldn’t create a new production.log until you restart your app. In that case, your app would just crash.

For more information on log-rotate, just read the man pages.