如何使用记录器在方法之外获取“打印”方法

How to get `prints` method outside the method using logger

我正在使用 gem 'logging'。我有很多方法无法使用记录器实例,但我想使用 class 之外的记录器从此方法获取日志消息。例如:

class Main
  def method
    p 'First log message'
    execute some steps
    p 'Another log message'
  end
end

如何使用我的记录器在 class 之外记录这两条消息: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

documentation 一样,您可以直接在 Logging class:

上调用相应的方法
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 的实例在任何 class 的任何实例中可用,可以使用类似的东西:

module IncludeLogger
  def logger 
    @logger ||= Logging.logger(STDOUT)
  end
end
Object.send :include, IncludeLogger

以上将向任何对象注入 logger 方法。