动态更改Ruby Logger的LogDevice [英] Dynamically change the LogDevice of Ruby Logger

查看:54
本文介绍了动态更改Ruby Logger的LogDevice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态更改Ruby LoggerLogDevice?

Is it possible to dynamically change the LogDevice of Ruby Logger?

如果是这样,它将允许对我现有的代码库进行一些不引人注目的更改.

If so, it would allow for some un-obtrusive changes to my existing codebase.

当前Ruby Logger使用StringIO作为LogDevice:

Currently Ruby Logger uses StringIO as the LogDevice:

@logDevice = StringIO.new("", "r+")
@log = Logger.new(@logDevice) // a reference to this is used by many objects
// both are instance vars

...

@log.info('some log') // Logging activity

...

// Before program ends, transmit logs to a server

可以动态更改LogDevice以继续记录到文件吗? (动态更改,因为最初文件名未知.)

Can LogDevice be dynamically changed to continue logging to a file? (dynamic change because initially the filename is not known.)

或者如果无法更改日志设备,StringIO对象可以开始写入文件吗?

Or if log device cannot be change can the StringIO object start writing to a file?

我可以写一个临时日志文件,而不是执行上述操作,但想检查是否可以完成上述操作,因为这对现有代码库的更改不那么引人注目.

Instead of doing the above, I could write to a temporary log file, but wanted to check if the above can be done because it would be a less obstrusive change to the existing codebase.

推荐答案

您给记录器的对象只需实现'write'和'close'方法,因此您可以轻松编写自己的'io':

The object you give to the logger just has to implement the 'write' and 'close' methods, so you can easily write your own 'io':

class MyIO
  def initialize
    @file = nil
    @history = StringIO.new "", "w"
  end

  def file=(filename)
    @file = File.open(filename, 'a+')
    @file.write @history.string if @history
    @history = nil
  end

  def write(data)
    @history.write(data) if @history
    @file.write(data) if @file
  end

  def close
    @file.close if @file
  end

结束

使用该实例创建记录器,并保留对该实例的引用.然后,只要知道文件名,就可以使用'file ='方法进行设置.

create the logger with an instance of that and keep a reference to the instance. Then, whenever you know the filename, just set it with the 'file=' method.

这篇关于动态更改Ruby Logger的LogDevice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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