views:

344

answers:

4

Is there a library or easy way to catch exceptions thrown in a Ruby program and log it to a file? I've looked over log4r and logger, but the docs on both don't provide any examples on how I would do this. I run this program remotely and lose handles to stdout and stderr, if that information helps at all.

What would you recommend?

A: 

Rescue from Exception. Something like this probably makes sense:

begin
  # run your code here ..
rescue Exception => exception
  # logger.error(...) ....
  raise exception
end

This will log the exception, and re-raise it so that the application actually raises an error in addition to the logging.

exception is an instance of Exception, take a look at the docs for information about what you can do with this object (such as accessing the backtrace).

August Lilleaas
Hmm, that's what I was afraid of having to do. The code involved is basically one class with a number of methods in it; would I just have to put a begin / rescue on every method or is there an easier way?
Chris Bunch
You're probably creating instances somewhere -- put the rescue block where you create the instances.
August Lilleaas
Putting it on the instance creation code won't do any good unless the error is in the creation. If you're wanting to catch any errors, globally, wrap your main body.
MarkusQ
I'm not talking about putting it in the "initialize" method, but the part of the code where you call ".new".
August Lilleaas
Ah, yes, that seems like that would work also. I'm a little concerned that I'd have to do that everywhere I interact with this class (since it's done over the network) and that monkeypatching, although a bit sketchy, gets the job done well enough. +1 for the help though and thanks again!
Chris Bunch
+5  A: 

If you want to take a walk on the wild side, try this:

class Exception
    alias real_init initialize
    def initialize(*args)
        real_init *args
        # log the error (self) or its args here
        end
    end

What this does is intercept the creation of new exception objects at the moment of creation.

MarkusQ
Thanks Markus! If the wild side works, I'm more than willing to walk it!
Chris Bunch
+2  A: 

If you're running a Rails app, the Exception Notification plugin is very handy.

John Douthat
Ah yes, I've definitely seen it, but my app in question isn't a Rails app. Thanks though!
Chris Bunch
A: 

Would it work if I did something like this:

begin
  main()
rescue Exception => e
  myCustomErrorLogger(e)
end

def main()
  # All the application code comes here.
end

What I need is to have all my uncaught exceptions move to the top-most level, and be caught there and subsequently recorded by the error logging function.

I'm trying this out now, but it would be great to have your suggestions.