puts vs logger in rails rake tasks

2019-03-08 02:45发布

In a rake task if I use puts command then I see the output on console. However I will not see that message in log file when app is deployed on production.

However if I say Rails.logger.info then in development mode I see nothing on console. I need to go to log file and tail that.

I would ideally like to use Rails.logger.info and in development mode inside the rake task, the output from logger should also be sent to console.

Is there a way to achieve that?

8条回答
姐就是有狂的资本
2楼-- · 2019-03-08 03:31

Code

For Rails 4 and newer, you can use Logger broadcast.

If you want to get both STDOUT and file logging for rake tasks in development mode, you can add this code into config/environments/development.rb :

  if File.basename($0) == 'rake'
    # http://stackoverflow.com/questions/2246141/puts-vs-logger-in-rails-rake-tasks
    log_file     = Rails.root.join("log", "#{Rails.env}.log")
    Rails.logger = ActiveSupport::Logger.new(log_file)
    Rails.logger.extend(ActiveSupport::Logger.broadcast(ActiveSupport::Logger.new(STDOUT)))
  end

Test

Here's a small Rake task to test the above code :

# lib/tasks/stdout_and_log.rake
namespace :stdout_and_log do
  desc "Test if Rails.logger outputs to STDOUT and log file"
  task :test => :environment do
    puts "HELLO FROM PUTS"
    Rails.logger.info "HELLO FROM LOGGER"
  end
end

Running rake stdout_and_log:test outputs

HELLO FROM PUTS
HELLO FROM LOGGER

while

HELLO FROM LOGGER

has been added to log/development.log.

Running rake stdout_and_log:test RAILS_ENV=production outputs

HELLO FROM PUTS

while

HELLO FROM LOGGER

has been added to log/production.log.

查看更多
闹够了就滚
3楼-- · 2019-03-08 03:33

Execute a background job with '&' and open script/console or whatever.. That way you can run multiple commands in the same window.

tail -f log/development.log &
script/console
Loading development environment (Rails 2.3.5)
>> Product.all
2011-03-10 11:56:00 18062 DEBUG  Product Load (6.0ms)  SELECT * FROM "products"
[<Product.1>,<Product.2>]

note Can get sloppy quickly when there is a lot of logging output.

查看更多
登录 后发表回答