4

New to Ruby I have a simple driver script right now that runs multiple test scripts in other ruby files. I have a method called RunScript() that runs the test scripts. The logger is created as a global variable in the driver script so that the test scripts in other files can use it. The logger logs to a log file in a directory.

What I want to be able to do is capture the logging outputs that happens while the method RunScript() is running only and store it as a String. So basically I want a String of log outputs for each Test Script and keep the log file which stores all the outputs.

sng
  • 129
  • 1
  • 2
  • 12

2 Answers2

5

I've done this in several different ways, and the most convenient I've found is to build a delegation object that routes messages to two or more loggers:

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 instantiated with two separate loggers, one that goes to the console, the other to a StringIO instance. The resulting LoggerTee instance is a drop-in replacement for any standard logger object.

Catnapper
  • 1,875
  • 10
  • 12
  • just for others who might have the same issue, I added @@capture_stringio.truncate(@@capturestringio.rewind) at the beginning of my run method so it will clear out the contents of the log for the next script. – sng May 03 '13 at 15:39
1

Indeed there is no way to get the content of the logger without importing extra things. Here is a different solution. Because logger has only several logging methods you may simply make your own and log and collect logs in that function

   #the_logger - regular logger
   #the_arr - a global array to keep your logs in
   #the_string - log string

   def log_info(the_logger, the_arr, the_string)

       the_logger.info(the_string);
       the_arr.push(the_string);
   end
   .....................and use global the_arr to get your output

Do this for 'debug', 'info', 'fatal' this is a simple way to use your log outputs as you run your program

lrl
  • 263
  • 4
  • 18