Class: MultiLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/nucleus/core/common/logging/multi_logger.rb

Overview

The MultiLogger allows to log messages not only to a file OR the stdout, but to both or even more loggers at the same time. The severity defaults to WARN but can be specified when instantiating the MultiLogger.

log_1 = Logger.new(STDOUT)
log_2 = Logger.new(File.open('/tmp/foo'))
multi_logger = MultiLogger.new(:level => Logger::WARN, :loggers => log_1)
multi_logger.add_logger(log_2)
multi_logger.warn('Something interesting happened.')

By Chris Lowder, see gist.github.com/clowder/3639600

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Object

Initialize the MultiLogger, specify the severity level for all loggers and add one or more loggers.

Parameters:

  • args (Hash) (defaults to: {})

    the options to create a message with.

Options Hash (args):

  • :level (Integer) — default: 2

    The severity level

  • :loggers (Array<Logger>) — default: []

    The loggers that are initially to be added



22
23
24
25
26
27
# File 'lib/nucleus/core/common/logging/multi_logger.rb', line 22

def initialize(args = {})
  @level = args[:level] || Logger::Severity::WARN
  @loggers = []

  Array(args[:loggers]).each { |logger| add_logger(logger) }
end

Instance Attribute Details

#levelObject

Returns the value of attribute level.



13
14
15
# File 'lib/nucleus/core/common/logging/multi_logger.rb', line 13

def level
  @level
end

Instance Method Details

#add_logger(logger) ⇒ Object

Add a logger to the MultiLogger and adjust its level to the MultiLogger’s current level.

Parameters:

  • logger (Logger)

    the logger to add to the MultiLogger instance



32
33
34
35
# File 'lib/nucleus/core/common/logging/multi_logger.rb', line 32

def add_logger(logger)
  logger.level = level
  @loggers << logger
end

#closeObject

Close each Logger of the MultiLogger instance



46
47
48
# File 'lib/nucleus/core/common/logging/multi_logger.rb', line 46

def close
  @loggers.map(&:close)
end