Ruby - 为不同的目标设置不同的日志级别

时间:2018-05-31 13:34:27

标签: ruby logging

想知道如何为不同的目标设置不同的日志级别。以下是我的Ruby代码,该代码向ConsoleFile写入一行。

# https://stackoverflow.com/a/6407200
class MultiIO
  def initialize(*targets)
    @targets = targets
  end

  def write(*args)
    @targets.each do |t|
      t.write(*args)
    end
  end

  def close
    @targets.each(&:close)
  end
end

module Logging
  def self.logger(logname, programname, debug = false)
    log_file = File.open(logname, "a")
    log_file.sync = true
    zlogger = Logger.new MultiIO.new(log_file, STDOUT)
    zlogger.level = Logger::INFO
    zlogger.progname = programname
    zlogger.formatter = proc do |serverity, datetime, progname, msg|
      "#{datetime.strftime('%Y-%m-%d %I:%M:%S %p %:::z %Z')} - #{serverity} - [#{progname}] | #{msg}\n"
    end

    zlogger
  end
end

如果找到特殊的env变量,我可以将级别设置为Debug, $logger.level = Logger::DEBUG if ENV['enable_debug_logs'] == 'true'

但是,不确定如何始终Debug行写入日志文件,并且只将Info行写入控制台。

有谁知道吗?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

由于日志级别是 logger 的属性,而不是IO的属性,因此我觉得你真正需要做的就是定义一个MultiLogger而不是MultiIO而不是class MultiLogger attr_reader :default_level, :default_progname, :default_formatter def initialize(**args) @default_level = args[:default_level] @default_progname = args[:default_progname] @default_formatter = args[:default_formatter] @loggers = [] Array(args[:loggers]).each { |logger| add_logger(logger) } end def add_logger(logger) logger.level = default_level if default_level logger.progname = default_progname if default_progname logger.formatter = default_formatter if default_formatter @loggers << logger end def close @loggers.map(&:close) end Logger::Severity.constants.each do |level| define_method(level.downcase) do |*args| @loggers.each { |logger| logger.send(__method__, args) } end # These methods are a bit weird in the context of a "multi-logger" with varying levels, # since they are now returning an `Array`; never a falsey value. # You may want to define them differently, e.g. `@loggers.all? {...}`, or use a non-predicate method name here. define_method("#{level.downcase}?".to_sym) do @loggers.map(&__method__) end end end # Usage: log_file = File.open(logname, "a") log_file.sync = true file_logger = Logger.new(log_file) console_logger = Logger.new(STDOUT) console_logger.level = Logger::INFO multi_logger = MultiLogger.new( default_progname: programname, default_formatter: proc do |severity, datetime, progname, msg| "#{datetime.strftime('%Y-%m-%d %I:%M:%S %p %:::z %Z')} - #{severity} - [#{progname}] | #{msg}\n" end, loggers: [file_logger, console_logger] ) 。有点像:

support:palette-v7:+'