Class: Aspire::Caching::CacheLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/aspire/caching/cache_logger.rb

Overview

A wrapper class for Logger adding utility methods

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger = nil) ⇒ CacheLogger

Initialises a new CacheLogger instance

Parameters:

  • logger (Logger) (defaults to: nil)

    the logger



38
39
40
# File 'lib/aspire/caching/cache_logger.rb', line 38

def initialize(logger = nil)
  self.logger = logger
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Delegates missing methods to the logger

Parameters:

  • method (Symbol)

    the method name

  • args (Array)

    the method arguments

  • block (Proc)

    the method code block

Returns:

  • (Object)

    the method result



19
20
21
22
23
24
25
26
# File 'lib/aspire/caching/cache_logger.rb', line 19

def method_missing(method, *args, &block)
  # Do not fail if logger is undefined
  return nil unless logger
  # Fail if logger does not respond to this method
  super unless logger.respond_to?(method)
  # Delegate to the logger method
  logger.public_send(method, *args, &block)
end

Instance Attribute Details

#loggerLogger

Returns the logger.

Returns:

  • (Logger)

    the logger



12
13
14
# File 'lib/aspire/caching/cache_logger.rb', line 12

def logger
  @logger
end

Instance Method Details

#log_exception(message, exception = nil, level: nil) ⇒ Object

Logs and raises an exception

Parameters:

  • message (String)

    the error message

  • exception (Class) (defaults to: nil)

    the class of the exception to be raised

  • level (Symbol) (defaults to: nil)

    the logger level (default: Logger::ERROR)

Raises:

  • (Aspire::Caching::Exceptions::Error)


47
48
49
50
# File 'lib/aspire/caching/cache_logger.rb', line 47

def log_exception(message, exception = nil, level: nil)
  log(level || Logger::ERROR, message)
  raise exception || Aspire::Exceptions::Error, message
end

#log_return(result, *args, **kwargs) ⇒ Object

Logs an event and returns its first argument

  • allows for compact code such as ‘return log_return(result, msg,…)’

Parameters:

  • result (Object)

    the return value of the method

Returns:

  • (Object)

    the result argument



57
58
59
60
# File 'lib/aspire/caching/cache_logger.rb', line 57

def log_return(result, *args, **kwargs)
  log(*args, **kwargs)
  result
end

#respond_to_missing?(method) ⇒ Boolean

Delegates missing method respond_to? to the wrapped logger

Parameters:

  • method (Symbol)

    the method name

Returns:

  • (Boolean)

    true if the wrapped logger responds to the method



31
32
33
34
# File 'lib/aspire/caching/cache_logger.rb', line 31

def respond_to_missing?(method)
  # If logger is undefined, all missing methods are accepted
  logger ? logger.respond_to?(method) : true
end