Используйте Logger стандартный библиотечный класс:
require 'logger'
logger = Logger.new 'my.log'
logger.info "Started."
foo = 42
logger.debug "foo is now #{foo}"
begin
foo = 1/0
rescue Exception => ex
logger.error "Caught exception: #{ex.inspect}"
end
logger.info "Finished."
Вывод на my.log :
# Logfile created on Tue May 18 14:55:35 +0200 2010 by logger.rb
I, [2010-05-18T14:55:35.021048 #8832] INFO -- : Started.
D, [2010-05-18T14:55:35.021141 #8832] DEBUG -- : foo is now 42
E, [2010-05-18T14:55:35.021231 #8832] ERROR -- : Caught exception: #<ZeroDivisionError: divided by 0>
I, [2010-05-18T14:55:35.021283 #8832] INFO -- : Finished.
Вы можете изменить форматирование так, как вам нравится, подклассифицировав Logger, затем
переопределить метод format_message:
class MyLogger < Logger
def format_message(severity, timestamp, progname, msg)
sprintf "%s,%03d %7s: %s\n",
timestamp.strftime("%Y-%m-%d %H:%M:%S"),
(timestamp.usec / 1000).to_s,
severity,
msg
end
end
logger = MyLogger.new 'my.log'
...
Выход:
# Logfile created on Tue May 18 15:07:42 +0200 2010 by logger.rb
2010-05-18 15:07:42,980 INFO: Started.
2010-05-18 15:07:42,980 DEBUG: foo is now 42
2010-05-18 15:07:42,980 ERROR: Caught exception: #<ZeroDivisionError: divided by 0>
2010-05-18 15:07:42,980 INFO: Finished.