puts vs logger in rails rake tasks

后端 未结 8 1532
情书的邮戳
情书的邮戳 2021-01-30 06:24

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 s

8条回答
  •  日久生厌
    2021-01-30 06:53

    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.

提交回复
热议问题