在方法中捕获记录器输出 [英] Capturing logger output inside a method

查看:35
本文介绍了在方法中捕获记录器输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

我已经用几种不同的方式完成了这项工作,我发现最方便的是构建一个将消息路由到两个或更多记录器的委托对象:

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

输出:

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 实例是任何标准记录器对象的直接替代品.

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.

这篇关于在方法中捕获记录器输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆