Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Logging Exceptions in Ruby

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?

like image 349
Chris Bunch Avatar asked Apr 19 '09 21:04

Chris Bunch


People also ask

How do you handle exceptions in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.

What is exception logging?

The exception log is a rolling collection of 4 files; when a file is full, data is added to the next file. When the last file has been filled, data starts to be added to the first file, overwriting the previous data there. This cycle of writing continues, ensuring that the newest data is retained.

Does raising an exception stop execution Ruby?

When you raise an exception in Ruby, the world stops and your program starts to shut down. If nothing stops the process, your program will eventually exit with an error message. Here's an example. In the code below, we try to divide by zero.

How do you create an exception in Ruby?

Exceptions are classes, just like everything else in Ruby! To create a new kind of exception, just create a class that inherits from StandardError, or one of its children. By convention, new exceptions have class names ending in "Error".


1 Answers

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.

like image 53
MarkusQ Avatar answered Sep 19 '22 18:09

MarkusQ