2013-04-30 55 views
4

Ruby新手我现在有一个简单的驱动程序脚本,它在其他ruby文件中运行多个测试脚本。我有一个名为RunScript()的方法来运行测试脚本。记录器作为驱动程序脚本中的全局变量创建,以便其他文件中的测试脚本可以使用它。记录器记录到目录中的日志文件。捕获方法内的记录器输出

我想要做的就是捕获在RunScript()方法仅运行时发生的日志输出,并将其存储为字符串。所以基本上我想为每个测试脚本提供一串日志输出,并保留存储所有输出的日志文件。

回答

5

我已经做了这几种不同的方式,我发现最方便的是要建立一个代表团对象,将消息路由到两个或更多的记录器:

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 

输出:

D, [2013-04-30T18:59:18.026285 #14533] DEBUG -- : Hello world 
D, [2013-04-30T18:59:18.026344 #14533] DEBUG -- : Hello world 

在这个例子中,LoggerTee类用两个独立的记录器实例化,一个进入控制台,另一个进入一个StringIO实例。生成的LoggerTee实例是任何标准记录器对象的替代品。

+0

这个工作完美一些修改后的感谢! – sng 2013-05-01 16:31:31

+0

只为其他可能有相同问题的人提供,我在运行方法的开始处添加了@@ capture_stringio.truncate(@@ capturestringio.rewind),以便清除下一个脚本的日志内容。 – sng 2013-05-03 15:39:15

1

确实没有办法在没有导入额外的东西的情况下获取记录器的内容。这是一个不同的解决方案。 由于记录仪只有几个测井方法,你可以简单地让自己和日志,并在功能

#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 

做此“调试”,“信息”,“致命的”收集日志,这是用一个简单的方法您的日志输出为你运行程序