Rotating Ruby on Rails Log Files Using Logrotate

If you don’t pay much attention to the size of your log files in your production apps, you might want to take a look! If left alone, files such as production.log can grow quite large and bog down your application or server’s performance. In Linux, there is a tool called logrotate to help you manage and archive your log files on a regular basis (on my installation of Ubuntu it was already there, I think it’s built-in. If not, try something like sudo apt-get install logrotate).

Let’s go through an example of how to rotate your production.log file. Navigate to /etc/logrotate.d. In there should be one or more config files, which specify what logs to rotate and with what options. My logrotate.d folder already had a few config files in there for apache2, mysql-server, etc. I created a new one and named it ruby.

Open up the newly created file (/etc/logrotate.d/ruby to be clear) and fill it with something like this:

/var/railsapps/myapp/shared/log/production.log {
daily
rotate 12
compress
missingok
copytruncate
}

So the first line points to whichever log file we want to deal with (I just used a sample path, yours is likely to differ). Something interesting you can do is instead of just doing this for production.log, put something like *.log and then logrotate will work its magic on any file in that folder which ends with .log!
Inside the brackets is just a sampling of the options you can put. I won’t go through all of them, just Google “logrotate options” or something like that and you’ll find all of them in no time, with thorough explanations. For the sake of this quick tutorial, I’ll explain a few:

  • daily: rotate log files daily (could have also said weekly or monthly)
  • rotate 12: keep 12 weeks worth of backlogs
  • compress: if you want your log files compressed to save diskspace (uses gzip)

You get the point. I read somewhere that if you are using Mongrel, you need the copytruncate option in order for the log to keep being written to, thus avoiding a restart (not sure of the accuracy of this statement, just a heads up!). To actually USE logrotate, all you have to do is wait for the time period you specified (if daily, wait for the next day) and rotation should happen automatically.

I hope this served as a good intro to rotating your Rails logs, if you have questions please post them!

Tags: , ,

Leave a Reply