Last Updated: February 25, 2016
·
633
· gus

Logging request params on exception

Debugging rails applications without the help of excellent tools such as airbrake can be a pain in the butt. While checking our logs we stumbled upon these kind of cryptic exceptions

 [#{timestamp}] FATAL Rails : 
TypeError (can't convert nil into String):
  # ... backtrace

We wanted to log the request parameters that led to this exception, fortunately we can invoke Rails.logger anywhere in our application and print something more useful

class ApplicationController <  ActionController::Base
  around_filter :log_report

  protected

  def log_report
    yield
  rescue => e
    logger.fatal generate_report(e)
    yield  
  end

  def generate_report(exception)
    "\r
    Exception: `#{exception}`\r
    Action: `#{controller_name}##{action_name}`\r
    Request: `#{request.method} #{request.fullpath}`\r
    Referrer: `#{request.referrer}`\r
    Cookies: `#{request.cookies}`"
  end
end