Rails回溯消音器不起作用,而过滤器则不起作用

时间:2015-03-20 14:35:42

标签: ruby-on-rails ruby-on-rails-4 backtrace

Fresh Rails 4.2设置。我想抑制长错误回溯。在下面的回溯日志中,第一行对我来说已足够,接下来的4行可以删除

ActionController::RoutingError (No route matches [GET] "/user"):
  actionpack (4.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  web-console (2.1.2) lib/web_console/middleware.rb:37:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.1) lib/rails/rack/logger.rb:38:in `call_app'

我在backtrace_silencers.rb

添加了一个新的消音器
# config/initializers/backtrace_silencers.rb
Rails.backtrace_cleaner.add_silencer { |line| line =~ /lib/ }

服务器重启后 - 没有任何反应,我仍然得到相同的回溯日志。 (应该删除与/lib/匹配的每一行:http://api.rubyonrails.org/classes/ActiveSupport/BacktraceCleaner.htm

完整性检查:

> line = "actionpack (4.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'"
=> "actionpack (4.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'"
> line =~ /lib/
=> 19

但过滤器有效:

# config/initializers/backtrace_silencers.rb
Rails.backtrace_cleaner.add_filter { |line| line.gsub('lib', 'yeah!') }

现在回溯看起来像这样:

ActionController::RoutingError (No route matches [GET] "/user"):
  actionpack (4.2.1) yeah!/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  web-console (2.1.2) yeah!/web_console/middleware.rb:37:in `call'
  actionpack (4.2.1) yeah!/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.1) yeah!/rails/rack/logger.rb:38:in `call_app'

欣赏如何使消音器工作的建议。干杯!

4 个答案:

答案 0 :(得分:4)

问题在于Minitest-Reporters gem(为Minitest输出添加颜色),它与Rails回溯过滤器混淆

要解决此问题,您需要将以下内容添加到test_helper.rb

Minitest::Reporters.use!(
  Minitest::Reporters::DefaultReporter.new,
  ENV,
  Minitest.backtrace_filter
)

此处描述的问题和解决方案详细信息:https://github.com/kern/minitest-reporters#caveats

答案 1 :(得分:3)

这是因为https://github.com/vipulnsward/rails/blob/ecc8f283cfc1b002b5141c527a827e74b770f2f0/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L155-L156

由于application_trace为空(这是因为错误不是来自用户代码而是路由错误),我们会回退到framework_trace,它不会过滤它(它只过滤噪音)。< / p>

你可以通过创建自己的log_formatter来达到你的监控。在development.rb和/或test.rb添加

config.log_formatter = SilentLogger.new
config.log_formatter.add_silencer { |line| line =~ /lib/ }

在模型中创建只需要方法call的简单类。在那里,您可以根据需要修改回溯。

class SilentLogger
  def initialize
    @silencers = []
  end

  def add_silencer(&block)
    @silencers << block
  end

  def call(severity, timestamp, progname, msg)
    backtrace = (String === msg) ? "#{msg}\n" : "#{msg.inspect}\n"

    return backtrace if @silencers.empty?

    @silencers.each do |s|
      backtrace = backtrace.split("\n").delete_if { |line| s.call(line) }
    end

    backtrace.join("\n")
  end
end

答案 2 :(得分:0)

在添加自己之前删除默认消音器:

Rails.backtrace_cleaner.remove_silencers!
Rails.backtrace_cleaner.add_silencer { |line| line =~ /lib/ }

答案 3 :(得分:0)

我遇到了类似的问题,这是由test_helper中的代码引起的:

def MiniTest.filter_backtrace(backtrace, prefix=nil)
  backtrace
end

它被添加到某个阶段和overrides this诊断错误。删除它删除了回溯。