log_subscriber.rb 2.6 KB
Newer Older
1 2 3 4 5
module ActionController
  class LogSubscriber < ActiveSupport::LogSubscriber
    INTERNAL_PARAMS = %w(controller action format _method only_path)

    def start_processing(event)
6 7
      return unless logger.info?

8 9
      payload = event.payload
      params  = payload[:params].except(*INTERNAL_PARAMS)
J
José Valim 已提交
10 11
      format  = payload[:format]
      format  = format.to_s.upcase if format.is_a?(Symbol)
12

13
      info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
14 15 16 17
      info "  Parameters: #{params.inspect}" unless params.empty?
    end

    def process_action(event)
18 19 20 21 22 23 24 25 26
      info do
        payload   = event.payload
        additions = ActionController::Base.log_process_action(payload)

        status = payload[:status]
        if status.nil? && payload[:exception].present?
          exception_class_name = payload[:exception].first
          status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
        end
27
        message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms".dup
28
        message << " (#{additions.join(" | ".freeze)})" unless additions.empty?
29
        message << "\n\n" if defined?(Rails.env) && Rails.env.development?
30

31
        message
32
      end
33 34
    end

35
    def halted_callback(event)
36
      info { "Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected" }
37 38
    end

39
    def send_file(event)
40
      info { "Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)" }
41 42 43
    end

    def redirect_to(event)
44
      info { "Redirected to #{event.payload[:location]}" }
45 46 47
    end

    def send_data(event)
48
      info { "Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)" }
49 50
    end

51
    def unpermitted_parameters(event)
52 53
      debug do
        unpermitted_keys = event.payload[:keys]
54
        "Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.map { |e| ":#{e}" }.join(", ")}"
55
      end
56 57
    end

58 59 60 61
    %w(write_fragment read_fragment exist_fragment?
       expire_fragment expire_page write_page).each do |method|
      class_eval <<-METHOD, __FILE__, __LINE__ + 1
        def #{method}(event)
62
          return unless logger.info? && ActionController::Base.enable_fragment_cache_logging
63
          key         = ActiveSupport::Cache.expand_cache_key(event.payload[:key] || event.payload[:path])
64
          human_name  = #{method.to_s.humanize.inspect}
65
          info("\#{human_name} \#{key} (\#{event.duration.round(1)}ms)")
66 67 68
        end
      METHOD
    end
69

70 71 72 73 74 75
    def logger
      ActionController::Base.logger
    end
  end
end

76
ActionController::LogSubscriber.attach_to :action_controller