How can I log all Ruby exception tracing with the default Rails logger?

I am working on a rails project and I am trying to get exceptions for logging in rails log files. I know I can raise logger.error $! to get the first line of the exception registered in the file. But I want the whole stack stack to register. How can I log an entire exception trace due to using the default recorder?

+34
ruby ruby-on-rails logging
Oct 23 '08 at 3:31
source share
6 answers
 logger.error $!.backtrace 

Also, do not forget that you can

 rescue ErrorType => error_name 

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

+38
Oct 25 '08 at 12:47
source share

How rails do it

 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.backtrace 250 if defined?(RAILS_ROOT) 251 backtrace.map { |line| line.sub RAILS_ROOT, '' } 252 else 253 backtrace 254 end 255 end 256 end 
+16
Oct 26 '08 at 10:40
source share

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

 # Rails.backtrace_cleaner.remove_silencers! 

This way you will get a complete writeback to the log, to the exception. This works for me in version 2.3.4.

+9
Oct 06 '09 at 18:57
source share

logger.error caller.join("\n") should do the trick.

+6
Oct 23 '08 at 3:42 a.m.
source share

In Rails, ActionController::Rescue deals with it. In my application manager actions, I use the log_error method from this module to pretty-shaped backtracking in logs:

 def foo_action # break something in here rescue log_error($!) # call firemen end 
+4
Nov 21 '08 at 9:08
source share

Here is how I would do it:

http://gist.github.com/127708

Here's the ri documentation for Exception # backtrace:

http://gist.github.com/127710

Please note that you can also use Kernel # caller, which also gives you the full trace (minus the short frame).

http://gist.github.com/127709

Also - note that if you are trying to catch all exceptions, you should get rid of Exception, not RuntimeError.

+3
Jun 11 '09 at 4:58
source share



All Articles