Home

May 13

Rails tip: Log which line called redirect_to

  • rails,
  • ruby

Here’s a quick Rails tip that has come in handy recently.

The Setup

Occasionally I need to trace a bug through the server logs. A user might have some completely un-reproducible error, or I might be trying to get a better idea of where to look for some vague problem. Often times this boils down to an unexpected redirect

For example:

Started GET "http://server.com/really_important_page" for 127.0.0.1
  Processing by HomeController#really_important_page as HTML
Redirected to https://server.com/not_the_page_you_wanted
Completed 302 Found in 1ms

Well - it redirected - informative enough for some simple actions that have a small number of before_filters that could cause a redirect, but it sure isn’t much help for some controller with half a dozen potential redirect_tos.

The Tip

Instead of just printing that a redirect occurred, let’s print the line that called redirect_to. In our application_controller.rb:

def redirect_to(options = {}, response_status = {})
  ::Rails.logger.error("Redirected by #{caller(1).first rescue "unknown"}")
  super(options, response_status)
end

Now we can clearly see why we hit that redirect:

Started GET "http://server.com/really_important_page" for 127.0.0.1
  Processing by HomeController#really_important_page as HTML
Redirected by app/controllers/application_controller.rb:53:in `ensure_random_bugs'
Redirected to https://server.com/not_the_page_you_wanted
Completed 302 Found in 1ms

Much better - now we know exactly which before_filter caused the redirect.

blog comments powered by Disqus