动态更改Ruby Logger的LogDevice [英] Dynamically change the LogDevice of Ruby Logger
问题描述
是否可以动态更改Ruby Logger
的LogDevice
?
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屋!