15

I have a daemon that runs constantly which fills up the log file(development.log or production.log) pretty quickly. What is the best way to delete the log file after certain size or delete the portion before certain day.

2

5 Answers 5

14
config.logger = Logger.new(config.log_path, 50, 1.megabyte)

but beware that multiple mongrels can have issues with this.

5
  • 1
    This is the most correct answer from a strictly Rails specific point of view. Apr 6, 2013 at 9:29
  • What does the 50 stand for? Jul 24, 2014 at 8:52
  • 50 means 50 files. See shift_age ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/…
    – Kirk
    Oct 12, 2014 at 15:31
  • 2
    Was just trying this. I had to change the syntax a bit. config.logger = Logger.new(config.paths['log'].first, 50, 1048576) because both config.log_path and 1.megabyte gave me errors.
    – Kirk
    Oct 12, 2014 at 15:44
  • @kirk try setting the log_path config.log_file = 'log/rpush.log' Feb 14, 2020 at 9:32
12

The best way is to set up log rotation, but how you do this is very platform dependent, so you should add a comment about what you're using, both for development and production.

For our apps running on Linux, we have a file /etc/logrotate.d/appname for each app, that looks something like this:

/path/to/rails_root_for_app/log/production.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 640 capistrano capistrano
}

This will move the log into a new file once a day, keeping a compressed backup file for each of the last 7 days.

If you just want to empty the file without keeping any of the data in it while the daemon is running, simply do this from a shell:

> /path/to/rails_root_for_app/log/development.log

This will truncate the file to 0 bytes length.

5

I prefer a monthly log file in my production.rb file

config.logger = Logger.new(config.log_path, 'monthly')
1

Or even better, if all your environments are on either Mac or Linux, and have /usr/sbin/rotatelogs, just use that. It's much more flexible, and doesn't have the data loss issue that logrotate has (even if you use copytruncate).

Add this inside config/application.rb (or just config/environments/production.rb if you only want rotation in prod):

log_pipe = IO.popen("/usr/sbin/rotatelogs #{Rails.root}/log/#{Rails.env}.%Y%m%d.log 86400", 'a')
config.logger = Logger.new(log_pipe)

(From this blog post)

0

Or you can delegate logging to syslog

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.