Logging Errors and Events in Ruby
Ruby standard library provides Ruby developers with logger mechanism. It relies on Logger class to accomplish events and errors capture into a file of stream. You can define global instance of the Logger class and then call it every time you need to record an event, error, or warning.
Logger class has several methods: debug, info, error, warn, and fatal. Here is an example that can handle both debug and error message within one method.
require ‘logger’
$LOG = Logger.new($stderr)
def my_method
$LOG.debug(“method starts)
begin
puts “Executing”
rescue
$LOG.error “Error just occurred”
end
return “Done”
end
We can selectively capture logs of specific type by setting log level in our global instance as show in the example below
$LOG.level = Logger::ERROR
Finally, Logger can log into file and you can set this file to expire after certain amount of time.