tagged_logger_proxy.rb 1.1 KB
Newer Older
1 2
module ActionCable
  module Connection
3 4
    # Allows the use of per-connection tags against the server logger. This wouldn't work using the traditional
    # <tt>ActiveSupport::TaggedLogging</tt> enhanced Rails.logger, as that logger will reset the tags between requests.
D
David Heinemeier Hansson 已提交
5
    # The connection is long-lived, so it needs its own set of tags for its independent duration.
6
    class TaggedLoggerProxy
7 8
      attr_reader :tags

9 10 11 12 13 14 15 16 17 18
      def initialize(logger, tags:)
        @logger = logger
        @tags = tags.flatten
      end

      def add_tags(*tags)
        @tags += tags.flatten
        @tags = @tags.uniq
      end

19 20 21 22 23 24 25 26 27
      def tag(logger)
        if logger.respond_to?(:tagged)
          current_tags = tags - logger.formatter.current_tags
          logger.tagged(*current_tags) { yield }
        else
          yield
        end
      end

28 29 30 31 32 33
      %i( debug info warn error fatal unknown ).each do |severity|
        define_method(severity) do |message|
          log severity, message
        end
      end

34 35
      protected
        def log(type, message)
36
          tag(@logger) { @logger.send type, message }
37 38 39 40
        end
    end
  end
end