Satya's blog - Overriding the Rails log file and rotating it

Sep 24 2007 09:28 Overriding the Rails log file and rotating it

Let's say you're like me and want your production log to be in /var/log/rails/yourapp.log, so you can keep your rails logs together for rotation etc. You still want to log your development Ruby on Rails log into log/development.log, as usual.

In config/environments.rb put this line:
config.logger = Logger.new("/var/log/rails/yourapp.log")
That's all.

UPDATE: The better way is to set
config.log_path='/var/log/rails/yourapp.log'
in config/environments/production.rb instead of config.logger as above.

You could have placed that line in config/environment.rb within the Rails::Initializer.run do |config| ... end block. That would have changed logging for all environments; development, production, and test.

Oh, you want to rotate the logs? (That's when you set up the logrotate package to periodically move your current log to yourapp.log.1 and truncate it, so eventually you end up with numbered or dated log files instead of one huge log file going back several months and occupying 200MB.) Easy enough, drop in a file /etc/logrotate.d/rails which contains:

weekly
missingok
rotate 52
compress
delaycompress
notifempty
sharedscripts
copytruncate
/var/log/rails/*.log {
    postrotate
        /etc/init.d/mongrel restart yourapp1
        /etc/init.d/mongrel restart yourapp2
    endscript
}

You don't need the postrotate..endscript block unless you want to restart mongrel after the log rotates. Since this script will cause weekly rotation, it's probably a good idea to restart mongrel as well. If you want to restart all the mongrel apps, you can of course leave off "yourapp1" etc, and just do:

    postrotate
        /etc/init.d/mongrel restart
    endscript

Last updated: Sep 24 2007 14:00

Tag: rails geeky