Welcome to the adventure

Huge Rails backtraces got you down?

Thursday May 31, 2007

I’ve got just the thing. Shorten them up!

While debugging an exception in a controller, after each page load I would get a 60 line backtrace, forcing me to scroll my console all the way up to see the relevant parts. I hate scrolling. I needed prettier & more relevant debug output.

It turns out you can customize how you want errors to be logged from inside your controllers — see rescue.rb in your rails distribution for more info. If you smack this sucker on your application.rb base-controller, your stack traces will be only 5 lines long.

  #
  # Custom logging of errors
  # What we're doing here is trimming down the backtrace of the inner exception
  # of TemplateErrors, because their backtrace is as long as a Tolstoy novel
  #
  # See rescue.rb in Rails for more information on how errors are handled/logged
  #
  def log_error(exception)
    if (exception.class == ActionView::TemplateError)
      e = exception.original_exception

      # trim down the stacktrace before we log it
      e.set_backtrace(e.backtrace[0..5])
    end
    # call original log_error defined in rescue.rb
    super
  end

Conceptually it’s not very elegant, but it’s simple enough. Good additions might be to not change the stacktrace if RAILS_ENV == 'production', and to make the number of stack trace lines configurable via a parameter (so you could define in environment.rb).

No Comments »

No comments yet.

Leave a comment