如何将输出发送到Rails控制台?

时间:2017-04-26 19:14:50

标签: ruby-on-rails ruby logging console

我正在使用Rails 5和Ruby 2.4。我想捕获错误的输出,在我的控制台上打印,所以我在我的一个app / service类中

rescue => e
  error = e
  msg = "#{e.message}\n"
  e.backtrace.each { |line|
    msg = "#{msg}\n#{line}"
  }
  logger.error msg
  raise e
end

但我收到以下错误

NameError: undefined local variable or method `logger' for #<RunCrawlersService:0x007fd14c2f1e10>
    from /Users/nataliab/Documents/workspace/myproject/app/services/run_mycustom_service.rb:34:in `rescue in block (2 levels) in run_all_crawlers'
    from /Users/nataliab/Documents/workspace/myproject/app/services/run_mycustom_service.rb:16:in `block (2 levels) in run_all_crawlers'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:348:in `run_task'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:337:in `block (3 levels) in create_worker'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `loop'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `block (2 levels) in create_worker'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `catch'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `block in create_worker'

如何正确地将输出发送到控制台?

1 个答案:

答案 0 :(得分:3)

您想使用Rails.logger

rescue => e
  Rails.logger.error "#{e.message}\n"
  e.backtrace.each { |line| Rails.logger.error "#{msg}\n#{line}" }
  raise e
end