开发者

How do I disable logging for a rake task?

I have a rake task that gets run as a cron job once a day. It performs some maintenance on a model that currently has 57k+ records in it. This adds hundreds of thousands of lines to the log each time the task is run for whichever environment it's currently in. (Currently it's just in development.)

How can I disable logging for a specific rake task or group of tasks, but leave logging开发者_Go百科 alone for the rest of the app and leave it alone for the model/methods that are called from the task?


The Rails logger is an ActiveSupport::BufferedLogger object, but can be re-assigned to any other kind of Logger object (or any object that responds to the Logger methods) that you wish, including something like this:

dev_null = Logger.new("/dev/null")
Rails.logger = dev_null
ActiveRecord::Base.logger = dev_null

Put these lines at the top of your Rake task and all logging output will be inexpensively sent to /dev/null, which is best explained by its Wikipedia article.


You can add this to the top of the task:

ActiveRecord::Base.logger.level = 2


If you have a cron job, you can redirect output to /dev/null like :

* * * * * rake whatever_task_blah_blah > /dev/null 2>&1


another possibility would be to have a config that is checking for an env var

# production.rb

Rails.application.configure do
  #...
  config.log_level = ENV["RAILS_LOG_LEVEL"].presence || :debug # default level

end

Then you can run anything prefixing the level you want

$> RAILS_LOG_LEVEL=info bin/rake my:rake:task
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜