Class: LoggerMultiplexor

Inherits:
Object
  • Object
show all
Defined in:
lib/logger_multiplexor.rb

Overview

Log to multiple streams.

The ‘logger’ module does not provide a logger that can log to multiple streams at once hence this hack. This class bundles multiple loggers so that they can be treated as one.

Example:

>>> logger = LoggerMultiplexor.new(STDOUT, 'development.log')
>>> logger.info('Hello') # Logs 'Hello' to both streams

Instance Method Summary collapse

Constructor Details

#initialize(*loggers) ⇒ LoggerMultiplexor

Returns a new instance of LoggerMultiplexor.



15
16
17
18
19
20
21
22
23
# File 'lib/logger_multiplexor.rb', line 15

def initialize(*loggers)
  @loggers = loggers.map do |stream|
    if stream.is_a?(Logger) || stream.is_a?(LoggerMultiplexor)
      stream
    else
      Logger.new(stream)
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/logger_multiplexor.rb', line 25

def method_missing(method_name, *args)
  if respond_to_missing?(method_name)
    @loggers.each { |logger| logger.send(method_name, *args) }
  else
    super
  end
end

Instance Method Details

#respond_to_missing?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/logger_multiplexor.rb', line 33

def respond_to_missing?(method_name)
  @loggers.all? do |logger|
    logger.respond_to?(method_name)
  end
end