I did this in several different ways, and the most convenient I found is to create a delegation object that sends messages to two or more registrars:
require 'stringio' require 'logger' class LoggerTee def initialize *loggers @loggers = loggers end def method_missing meth, *args, &block @loggers.each { |logger| logger.send(meth, *args, &block) } end end capture_stringio = StringIO.new console_log = Logger.new(STDOUT) string_log = Logger.new(capture_stringio) log = LoggerTee.new(console_log, string_log) log.debug 'Hello world' puts capture_stringio.string
Output:
D, [2013-04-30T18:59:18.026285 #14533] DEBUG -- : Hello world D, [2013-04-30T18:59:18.026344 #14533] DEBUG -- : Hello world
In this example, the LoggerTee class is created with two separate loggers, one of which goes to the console, and the other to the StringIO instance. The resulting LoggerTee instance is a replacement for any standard log object.
source share