aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/tagged_logging.rb
blob: 0d8504bc1f826e8067d37232d219d85f0e67266e (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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


    def fatal(progname = nil, &block)
      add(@logger.class::FATAL, progname, &block)
    end

    def error(progname = nil, &block)
      add(@logger.class::ERROR, progname, &block)
    end

    def warn(progname = nil, &block)
      add(@logger.class::WARN, progname, &block)
    end

    def info(progname = nil, &block)
      add(@logger.class::INFO, progname, &block)
    end

    def debug(progname = nil, &block)
      add(@logger.class::DEBUG, progname, &block)
    end

    def unknown(progname = nil, &block)
      add(@logger.class::UNKNOWN, progname, &block)
    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