Your Rails application log files can grow forever if you don’t do anything to avoid it, making it more difficult to search them for info when things go wrong or even making your server run out of disk space.

But it’s easy to keep your log files in check with logrotate. First make sure it’s installed in your system, in Ubuntu it’s part of the default installation, but if for some reason it isn’t there install it with:

sudo apt-get install logrotate

Then you can add your configuration either in /etc/logrotate.conf or in a separate file inside /etc/logrotate.d.

For this example create the new file /etc/logrotate.d/my_rails_app and paste the following there:

/path/to/rails_app/log/*.log {
  su rails_app_user rails_app_user
  daily
  missingok
  rotate 7
  compress
  delaycompress
  notifempty
  copytruncate
}

This will rotate *.log files inside /path/to/rails_app/log/ daily, and keep logs for 7 days.

  • su: tells logrotate which user/group should be used for rotation
  • daily/weekly/monthly: tells logrotate how often to rotate files
  • missingok: ignore the file if it doesn’t exist
  • rotate N: how many periods to keep (of the ones defined in the second line: days, weeks or months)
  • compress: compress rotated log files
  • delaycompress: compress the rotated log files next time the log file is rotated, to make sure it doesn’t interfere with the server being run
  • notifempty: skip rotation if the log file is empty
  • copytruncate: makes a backup copy of the current log and then clears the log file for continued writing, this way you don’t need to restart the server each time the log is rotated

Another example that rotates logs weekly and keeps the logs for a year (52 weeks):

/path/to/rails_app/tmp/log/*.log {
  su rails_app_user rails_app_user
  weekly
  missingok
  rotate 52
  compress
  delaycompress
  notifempty
  copytruncate
}

End note: if you’re using the gem rails_12factor it will make your Rails app output its logging to stdout so your log files will always be empty, remove it to avoid that.