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

Rails backtrace silencers do not work, while filters do

新鲜Rails4.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'

希望得到有关如何使消音器起作用的建议。干杯!

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

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

问题出在 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

我有一个类似的问题,这是由test_helper中的这段代码引起的:

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

添加它是为了在某个阶段诊断错误,overrides this。删除删除回溯。

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

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

您可以通过创建自己的 log_formatter 来达到自己的目的。在你的 development.rb and/or test.rb 添加

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

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

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