aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/tagged_logging.rb
blob: 0cabb528eff5ec9bb678cfaf8062d06f4f6512ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
require 'logger'

module ActiveSupport
  # 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.
  class TaggedLogging
    def initialize(logger)
      @logger = logger
      @tags   = []
    end

    def tagged(*tags)
      new_tags = Array.wrap(tags).flatten
      @tags += new_tags
      yield
    ensure
      new_tags.size.times { @tags.pop }
    end


    def add(severity, message = nil, progname = nil, &block)
      @logger.add(severity, "#{tags}#{message}", progname, &block)
    end

    %w( fatal error warn info debug unkown ).each do |severity|
      eval <<-EOM, nil, __FILE__, __LINE__ + 1
        def #{severity}(progname = nil, &block)
          add(Logger::#{severity.upcase}, progname, &block)
        end
      EOM
    end


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

    private
      def tags
        if @tags.any?
          @tags.collect { |tag| "[#{tag}]" }.join(" ") + " "
        end
      end
  end
end