Zabba
Zabba

Reputation: 65467

How to log exceptions automatically in Rails?

If there is an exception in a controller action and rescue is used, Rails does not show the exception either in the browser (which is O.K), nor does it write the exception to the log file.

Is there a way to get Rails to write the exception to the log file in this case?

Example:

def some_action
  2/0
rescue
  #this code is called, but Rails does not write the exception to the log
end

Upvotes: 1

Views: 4912

Answers (2)

Zabba
Zabba

Reputation: 65467

I ended up using rescue_from in the ApplicationController, logging the exception message and backtrace, and then using params[:controller] and params[:action] to determine what controller/action to redirect to.

For example, if PostsController#show exception'ed out, I would redirect to PostsController#index from within rescue_from. It's been working so far, so it doesn't seem to be a bad thing to do redirect_to from within rescue_from. Time will let me know, I'm sure! (Just need to make sure that my redirects don't cause some infinite loops!)

And just in someone is interested in this hack (try at your own risk!):

class ApplicationController < ActionController::Base

  def determine_redirect_to_path(controller,action)
    ...
  end

  rescue_from StandardError do |exception|    
    backtrace_size = exception.backtrace.size
    if backtrace_size >= 2 then max_range = 2
    elsif backtrace_size >= 1 then max_range = 1
    end
    if max_range > 0      
      s = "rescued_from:: #{params[:controller]}##{params[:action]}: #{exception.inspect}\n#{exception.backtrace[0..max_range].to_s}\n"
      logger.error s
    end
    redirect_to determine_redirect_to_path(params[:controller],params[:action])
  end      
end  

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96934

You're rescuing the exception, so it won't log it because nothing bad actually happened since it was, in fact, "rescued".

You can put the following code within your rescue block to put an entry in the log:

logger.warn "Exception rescued!"

You can read more about using the logger in the Rails Guides.

Upvotes: 4

Related Questions