Rails backtrace silencers do not work, while filters do

泄露秘密 提交于 2019-12-01 16:28:38

Problem was with Minitest-Reporters gem (adds colors to Minitest output), it messes up with Rails backtrace filters

To fix you need to add the following to test_helper.rb

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

Problem and solution details described here: https://github.com/kern/minitest-reporters#caveats

This is because of https://github.com/vipulnsward/rails/blob/ecc8f283cfc1b002b5141c527a827e74b770f2f0/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L155-L156

Since application_trace is empty(This is because error is not from user code but route error), we are falling back to framework_trace, which does not filter it (it filters only noise).

You can reach your gaol it with creating your own log_formatter. In your development.rb and/or test.rb add

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

And create simple class in models with only method call required. There you can modify your backtrace as you wish.

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

Remove default silencers before add own:

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

I had a similar problem, which was caused by this code in test_helper:

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

It was added to diagnose the error at some stage and overrides this. Removing that removed the backtrace.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!