Class: Sparrow::Logger

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

Overview

Simple Logger class to handle behavior’s in Rails and Rack environment without the need to depend on an a “real” Logger to be available under the hood.

If the middleware is running in a Rails environment (i.e. the Rails-constant is defined), is will delegate all its method calls to the Rails logger. Otherwise a simple log to STDOUT will get triggered using the method name as log level and the argument as message.

Examples:

Sparrow::Logger.debug('this is a debug message')

when in a Rails env equals

Rails.logger.debug('this is a debug message')

when not in a Rails environment the same call equals

ActiveSupport::Logger.debug("this is a debug message")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enabled) ⇒ Logger

Initialize the Logger Enables the logging only if enabled is truthy. Otherwise the logger will do nothing at all.

Parameters:

  • enabled (Boolean)

    logging enabled



40
41
42
43
44
45
46
47
# File 'lib/sparrow/logger.rb', line 40

def initialize(enabled)
  self.enabled = enabled
  @logger = if defined?(Rails)
              Rails.logger
            else
              ::Logger.new(STDOUT)
            end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



49
50
51
# File 'lib/sparrow/logger.rb', line 49

def method_missing(method_name, *args)
  logger.public_send(method_name, *args) if enabled?
end

Instance Attribute Details

#enabledBoolean Also known as: enabled?

Returns logging enabled.

Returns:

  • (Boolean)

    logging enabled



27
28
29
# File 'lib/sparrow/logger.rb', line 27

def enabled
  @enabled
end

#loggerObject (readonly)

Wrapped Logger class the Rails logger or a plain ActiveSupport::Logger instance using STDOUT



33
34
35
# File 'lib/sparrow/logger.rb', line 33

def logger
  @logger
end