Automatically Logging Exceptions in Ruby

2019-03-29 03:43发布

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?

5条回答
做个烂人
2楼-- · 2019-03-29 04:22

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).

查看更多
祖国的老花朵
3楼-- · 2019-03-29 04:24

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.

查看更多
萌系小妹纸
4楼-- · 2019-03-29 04:30

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

查看更多
Melony?
5楼-- · 2019-03-29 04:32

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

This will intercept the creation of new exception objects at the moment of creation.

查看更多
祖国的老花朵
6楼-- · 2019-03-29 04:35

You can tweak the code of the class Exception in the part that puts to stdout the reason and the backtrace.

Don't forget to check if the logger can be null, the exception can be throwed before (or while) the logger its created.

查看更多
登录 后发表回答