How do I log the entire trace back of a Ruby exception using the default Rails logger? How do I log the entire trace back of a Ruby exception using the default Rails logger? ruby ruby

How do I log the entire trace back of a Ruby exception using the default Rails logger?


logger.error $!.backtrace

Also, don't forget you can

rescue ErrorType => error_name

to give your error a variable name other than the default $!.


The way rails does it is

137             logger.fatal(138               "\n\n#{exception.class} (#{exception.message}):\n    " +139               clean_backtrace(exception).join("\n    ") +140               "\n\n"141             )248       def clean_backtrace(exception)249         if backtrace = exception.backtrace250           if defined?(RAILS_ROOT)251             backtrace.map { |line| line.sub RAILS_ROOT, '' }252           else253             backtrace254           end255         end256       end


In later versions of Rails, simply uncomment the following line in RAIL_ROOT/config/initializers/backtrace_silencers.rb (or add this file itself if it's not there):

# Rails.backtrace_cleaner.remove_silencers!

This way you get the full backtrace written to the log on an exception. This works for me in v2.3.4.