Rails错误处理/日志记录:简化的回溯

时间:2015-01-14 11:59:25

标签: ruby-on-rails ruby ruby-on-rails-3 logging error-handling

我正在为我的Rails应用程序开发错误记录系统,以接收任何隐藏的错误。

到目前为止,我已经在我的ApplicationController上使用rescue_from实现了这一点:(注意我正处于试验阶段,因此我只将结果输出到控制台)

   rescue_from Exception, with: :log_exception

   private
    def log_exception exception
      puts("Exception at #{Time.now.strftime('%d %b %Y, %H:%M')}")
      puts exception
      puts exception.backtrace.join "\n"
      raise exception
    end

我遇到的问题是exception.backtrace。它会输出一大堆无用的深度跟踪,看起来像这样

/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activemodel-3.2.13/lib/active_model/attribute_methods.rb:407:in `method_missing'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activerecord-3.2.13/lib/active_record/attribute_methods.rb:149:in `method_missing'
/Users/marcoprins/Desktop/Project/tillyoudrop/app/models/order.rb:105:in `cancel!'
/Users/marcoprins/Desktop/Project/tillyoudrop/app/controllers/admin/orders_controller.rb:97:in `cancel'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-3.2.13/lib/action_controller/metal/implicit_render.rb:4:in `send_action'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-3.2.13/lib/abstract_controller/base.rb:167:in `process_action'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-3.2.13/lib/action_controller/metal/rendering.rb:10:in `process_action'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/actionpack-3.2.13/lib/abstract_controller/callbacks.rb:18:in `block in process_action'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:436:in `_run__4209411771832668003__process_action__2626133284113442857__callbacks'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:405:in `__run_callback'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
/Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:81:in `run_callbacks'

它持续数英里。

我希望我的错误日志文件看起来干净可读,所以我想要的只是本例的第3行和第4行,或者更确切地说,Rails在错误页面输出的确切行,(见图片)部分这告诉我错误来自我的代码中的位置。

Rails error page

如何访问这些行? exception对象上是否包含属性?

1 个答案:

答案 0 :(得分:1)

通过与要提取或忽略的文件/目录进行模式匹配来拒绝或选择某些行。例如,如果您要忽略/gems/中的步骤,则:

exception.backtrace.reject{|l| l =~ %r|\A[^:]*/gems/|}

如果您只想要/app/目录中的步骤,那么:

exception.backtrace.select{|l| l =~ %r|\A[^:]*/app/|}

实际上,您应该使用backtrace_locations而不是backtrace,这样可以在不使用正则表达式的情况下直接访问路径,但目前backtrace_locations充满了错误,而且使用它是不切实际的。