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?
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.
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.
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With