aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/rack/logger.rb
blob: 798fb3267783f7bea78cf37319beb329aac57c03 (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
require 'active_support/core_ext/time/conversions'
require 'active_support/core_ext/object/blank'

module Rails
  module Rack
    # Log the request started and flush all loggers after it.
    class Logger < ActiveSupport::LogSubscriber
      def initialize(app, tags=nil)
        @app, @tags = app, tags.presence
      end

      def call(env)
        if @tags && Rails.logger.respond_to?(:tagged)
          Rails.logger.tagged(compute_tags(env)) { call_app(env) }
        else
          call_app(env)
        end
      end

    protected

      def call_app(env)
        request = ActionDispatch::Request.new(env)
        path = request.filtered_path
        Rails.logger.info "\n\n"
        Rails.logger.info "Started #{request.request_method} \"#{path}\" for #{request.ip} at #{Time.now.to_default_s}"
        @app.call(env)
      ensure
        ActiveSupport::LogSubscriber.flush_all!
      end

      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