Class: ActiveSupport::TaggedLogging

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

Overview

Wraps any standard Logger class to provide tagging capabilities. Examples:

Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
Logger.tagged("BCX") { Logger.info "Stuff" }                            # Logs "[BCX] Stuff"
Logger.tagged("BCX", "Jason") { Logger.info "Stuff" }                   # Logs "[BCX] [Jason] Stuff"
Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"

This is used by the default Rails.logger as configured by Railties to make it easy to stamp log lines with subdomains, request ids, and anything else to aid debugging of multi-user production applications.

Instance Method Summary collapse

Constructor Details

#initialize(logger) ⇒ TaggedLogging

Returns a new instance of TaggedLogging.



16
17
18
# File 'lib/active_support/tagged_logging.rb', line 16

def initialize(logger)
  @logger = logger
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



64
65
66
# File 'lib/active_support/tagged_logging.rb', line 64

def method_missing(method, *args)
  @logger.send(method, *args)
end

Instance Method Details

#add(severity, message = nil, progname = nil, &block) ⇒ Object



46
47
48
49
# File 'lib/active_support/tagged_logging.rb', line 46

def add(severity, message = nil, progname = nil, &block)
  message = (block_given? ? block.call : progname) if message.nil?
  @logger.add(severity, "#{tags_text}#{message}", progname)
end

#clear_tags!Object



37
38
39
# File 'lib/active_support/tagged_logging.rb', line 37

def clear_tags!
  current_tags.clear
end

#flushObject



59
60
61
62
# File 'lib/active_support/tagged_logging.rb', line 59

def flush
  clear_tags!
  @logger.flush if @logger.respond_to?(:flush)
end

#pop_tags(size = 1) ⇒ Object



33
34
35
# File 'lib/active_support/tagged_logging.rb', line 33

def pop_tags(size = 1)
  current_tags.pop size
end

#push_tags(*tags) ⇒ Object



27
28
29
30
31
# File 'lib/active_support/tagged_logging.rb', line 27

def push_tags(*tags)
  tags.flatten.reject(&:blank?).tap do |new_tags|
    current_tags.concat new_tags
  end
end

#silence(temporary_level = Logger::ERROR, &block) ⇒ Object



41
42
43
# File 'lib/active_support/tagged_logging.rb', line 41

def silence(temporary_level = Logger::ERROR, &block)
  @logger.silence(temporary_level, &block)
end

#tagged(*tags) ⇒ Object



20
21
22
23
24
25
# File 'lib/active_support/tagged_logging.rb', line 20

def tagged(*tags)
  new_tags = push_tags(*tags)
  yield self
ensure
  pop_tags(new_tags.size)
end