Capturing logger output inside a method

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

What I want to do is to capture the log output that occurs when only RunScript () is running and saves it as a String. So basically, I want the line of each of the log outputs for each test script to store the log file in which all the outputs are stored.

+4
source share
2 answers

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.

+5
source

Indeed, there is no way to get the contents of the registrar without importing unnecessary things. Here is another solution. Since logger has only a few logging methods, you can just make your own and log and collect logs in this 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 an easy way to use log outputs when starting your program.

+1
source

All Articles