Getting the full backtrace for Rails deprecation warnings
Recently I was working on a Rails app that was throwing a deprecation warning. The warning was coming from a gem, and I wanted to see the full backtrace to figure out where it was coming from.
Logging the full backtrace
Rails allows you to configure how to handle deprecation warnings. By default, it logs the warning to the console. You can change this behavior by setting Rails.application.config.active_support.deprecation
to a different value.
# config/environments/development.rb
Rails.application.configure do
config.active_support.deprecation = :log
end
If we change this to :raise
, Rails will raise an exception instead of logging the warning. This exception will include the full backtrace.
# config/environments/development.rb
Rails.application.configure do
config.active_support.deprecation = :raise
end
That’s one way to get the full backtrace for deprecation warnings, but it might be a bit too aggressive. If you want to keep logging the warnings, but also get the full backtrace, you can use the :notify
option.
# config/environments/development.rb
Rails.application.configure do
config.active_support.deprecation = :notify
end
This will send an ActiveSupport::Notification
, which we can intercept, to log the full backtrace.
# config/initializers/deprecation_backtrace.rb
ActiveSupport::Notifications.subscribe('deprecation.rails') do |name, start, finish, id, payload|
Rails.logger.warn("DEPRECATION WARNING: #{payload[:message]}")
Rails.logger.warn(payload[:callstack].join("\n "))
end
We could also tweak this to send the notification to an exception tracking service, so we’re aware of deprecation warnings in production, as we may not catch all deprecation warnings in developement.
Conclusion
Hopefully this helps you track down deprecation warnings in your Rails app, and fix those warnings before they become errors in the next version of Rails.