puts vs logger in rails rake tasks

后端 未结 8 1529
情书的邮戳
情书的邮戳 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:51

    I'd say that using Rails.logger.info is the way to go.

    You won't be able to see it in the server console because it won't run via the server. Just open up a new console and tail -f the log file, it'll do the trick.

    Many users are aware of the UNIX® command 'tail', which can be used to display the last few lines of a large file. This can be useful for viewing log files, etc.

    Even more useful in some situations, is the '-f' parameter to the 'tail' command. This causes tail to 'follow' the output of the file. Initially, the response will be the same as for 'tail' on its own - the last few lines of the file will be displayed. However, the command does not return to the prompt, and instead, continues to 'follow' the file. When additional lines are added to the file, they will be displayed on the terminal. This is very useful for watching log files, or any other file which may be appended over time. Type 'man tail' for more details on this and other tail options.

    (via)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题