# 1) 创建对象
bc = BacktraceCleaner.new
# 2) 添加规则。可指定'替换'某字符串信息:
bc.add_filter { |line| line.gsub(Rails.root, '') }
# 2) 添加规则。可指定'删除'某 gem 信息:
bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
# 3) 执行过滤。从 exception.backtrace 里过滤掉符合规则的字符串
bc.clean(exception.backtrace) #
# config/initializers/backtrace_silencers.rb
Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
Rails.backtrace_cleaner
=> #<Rails::BacktraceCleaner:0x007ff859bed328
@filters=
[#<Proc:0x007ff859bed238@/Users/.../lib/rails/backtrace_cleaner.rb:10>,
#<Proc:0x007ff859bed210@/Users/.../lib/rails/backtrace_cleaner.rb:11>,
#<Proc:0x007ff859bed1c0@/Users/.../lib/rails/backtrace_cleaner.rb:12>,
#<Proc:0x007ff859bec450@/Users/.../lib/rails/backtrace_cleaner.rb:26>],
@silencers=
[#<Proc:0x007ff859bec428@/Users/.../lib/rails/backtrace_cleaner.rb:15>]>
# railties/lib/rails/backtrace_cleaner.rb
module Rails
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
# ...
end
end
# railties/lib/rails.rb
def backtrace_cleaner
@backtrace_cleaner ||= begin
require 'rails/backtrace_cleaner'
Rails::BacktraceCleaner.new
end
end
# railties/lib/application.rb
def env_config
# ...
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
# ...
end
# action_dispatch/middleware/exception_wrapper.rb
def backtrace_cleaner
@backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
end
def clean_backtrace(*args)
if backtrace_cleaner
backtrace_cleaner.clean(backtrace, *args)
else
backtrace
end
end