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.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…