Module: RooOnRails::ContextLogging

Defined in:
lib/roo_on_rails/context_logging.rb

Overview

Wraps any standard logger to provide context, similar to ‘ActiveSupport::TaggedLogging` but with key/value pairs that are appended to the end of the text.

logger = RooOnRails::ContextLogging.new(ActiveSupport::Logger.new($stdout))
logger.with(a: 1, b: 2) { logger.info 'Stuff' }                   # Logs "Stuff a=1 b=2"
logger.with(a: 1) { logger.with(b: 2) { logger.info('Stuff') } }  # Logs "Stuff a=1 b=2"

The above methods persist the context in thread local storage so it will be attached to any logs made within the scope of the block, even in called methods. However, if your context only applies to the current log then you can chain off the ‘with` method.

logger.with(a: 1, b: 2).info('Stuff')                   # Logs "Stuff a=1 b=2"
logger.with(a: 1) { logger.with(b: 2).info('Stuff')  }  # Logs "Stuff a=1 b=2"

Hashes, arrays and any complex object that supports ‘#to_json` will be output in escaped JSON format so that it can be parsed out of the attribute values.

Defined Under Namespace

Modules: Formatter Classes: LoggerProxy

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(logger) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/roo_on_rails/context_logging.rb', line 77

def self.new(logger)
  warn 'RooOnRails::ContextLogging is deprecated. Please use Rails.logger.'
  # Ensure we set a default formatter so we aren't extending nil!
  logger.formatter ||=
    if ActiveSupport::VERSION::MAJOR >= 4
      require 'active_support/logger'
      ActiveSupport::Logger::SimpleFormatter.new
    else
      require 'active_support/core_ext/logger'
      ::Logger::SimpleFormatter.new
    end
  logger.formatter.extend(Formatter)
  logger.extend(self)
end

Instance Method Details

#flushObject



102
103
104
105
# File 'lib/roo_on_rails/context_logging.rb', line 102

def flush
  clear_context!
  super if defined?(super)
end

#with(**context) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/roo_on_rails/context_logging.rb', line 94

def with(**context)
  if block_given?
    formatter.with(**context) { yield self }
  else
    LoggerProxy.new(self, context)
  end
end