module RooOnRails::ContextLogging
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.
Public Class Methods
new(logger)
click to toggle source
# 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
Public Instance Methods
flush()
click to toggle source
Calls superclass method
# File lib/roo_on_rails/context_logging.rb, line 102 def flush clear_context! super if defined?(super) end
with(**context) { |self| ... }
click to toggle source
# 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