aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/rack/tagged_logging.rb
blob: c519d7c3e6fde4d85ba1b6b3640b6f4693939d13 (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
module Rails
  module Rack
    # Enables easy tagging of any logging activity that occurs within the Rails request cycle. The tags are configured via the
    # config.log_tags setting. The tags can either be strings, procs taking a request argument, or symbols representing method
    # names on request (so :uuid will result in request.uuid being added as a tag).
    class TaggedLogging
      def initialize(app, tags = nil)
        @app, @tags = app, tags
      end

      def call(env)
        if @tags
          Rails.logger.tagged(compute_tags(env)) { @app.call(env) }
        else
          @app.call(env)
        end
      end
      
      private
        def compute_tags(env)
          request = ActionDispatch::Request.new(env)

          @tags.collect do |tag|
            case tag
            when Proc
              tag.call(request)
            when Symbol
              request.send(tag)
            else
              tag
            end
          end
        end
    end
  end
end