我正在使用gem 'logging'
。我有很多方法,我不能使用logger实例,但我希望使用类外的logger从这个方法获取日志消息。例如:
class Main
def method
p 'First log message'
execute some steps
p 'Another log message'
end
end
如何使用我的记录器将这两条消息记录在类之外:logger.warn(method)
但是作为单独的日志:
... WARN: 'First log message'
... WARN: 'Another log message'
更新 可能的解决方案是使记录器成为全局:
module Kernel
def logger
@logger ||= Logging.logger(STDOUT)
end
end
更新2:
module Logging
module Loggable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def logger
Logging.logger(STDOUT)
end
end
def logger
self.class.logger
end
end
end
Object.send :include, Logging::Loggable
答案 0 :(得分:1)
从documentation开始,您可以直接在Logging
类上调用相应的方法:
Logging.logger(STDOUT).warn 'ghgh'
W, [2015-03-07T09:04:30.601189 #19126] WARN : ghgh
或者您可以声明全局变量:
$logger = Logging.logger(STDOUT)
$logger.warn 'ghgh'
或者您可以在方法中查询记录器实例:
lg = Logging.logger['my-logger']
lg.warn 'ghgh'
希望它有所帮助。
UPD 要在任何类的任何实例中提供Logging
的实例,可以使用以下内容:
module IncludeLogger
def logger
@logger ||= Logging.logger(STDOUT)
end
end
Object.send :include, IncludeLogger
上面会将logger
方法注入任何对象。