This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Adding Logging To Your Application
CodeExpectedActual
require 'logger'
$LOG = Logger.new($stderr)
def divide(numerator, denominator)
  $LOG.debug("Numerator: #{numerator}, denominator #{denominator}")
  begin
    result = numerator / denominator
  rescue Exception => e
    $LOG.error "Error in division!: #{e}"
    result = nil
  end
  return result
end
divide(10, 2)
D, [2006-03-31T19:35:01.043938 #18088] DEBUG -- : Numerator: 10, denominator 2
divide(10, 0)
D, [2006-03-31T19:35:01.045230 #18088] DEBUG -- : Numerator: 10, denominator 0
E, [2006-03-31T19:35:01.045495 #18088] ERROR -- : Error in division!: divided by 0
divide(10, 2)
5 5
divide(10, 0)
E, [2006-03-31T19:35:01.047861 #18088] ERROR -- : Error in division!: divided by 0
Logger.new('this_month.log', 'monthly')
Keep data for today and the past 20 days.
Logger.new('application.log', 20, 'daily')
Start the log over whenever the log exceeds 100 megabytes in size.
Logger.new('application.log', 20, 'daily')
class Logger
  class Formatter
    Format = "%s [%s] %s %s\n"
    def call(severity, time, progname, msg)
      Format % [severity, format_datetime(time), progname, msg]
    end
  end
end
$LOG.error('This is much shorter.')
ERROR [2006-03-31T19:35:01.058646 ]  This is much shorter.