summaryrefslogtreecommitdiff
path: root/lib/gitlab/lograge/custom_options.rb
blob: 17a36c292c0f30476e108dc7f98d364b8ed24564 (plain)
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
# frozen_string_literal: true

module Gitlab
  module Lograge
    module CustomOptions
      include ::Gitlab::Logging::CloudflareHelper

      LIMITED_ARRAY_SENTINEL = { key: 'truncated', value: '...' }.freeze
      IGNORE_PARAMS = Set.new(%w(controller action format)).freeze

      def self.call(event)
        params = event
          .payload[:params]
          .each_with_object([]) { |(k, v), array| array << { key: k, value: v } unless IGNORE_PARAMS.include?(k) }
        payload = {
          time: Time.now.utc.iso8601(3),
          params: Gitlab::Utils::LogLimitedArray.log_limited_array(params, sentinel: LIMITED_ARRAY_SENTINEL),
          remote_ip: event.payload[:remote_ip],
          user_id: event.payload[:user_id],
          username: event.payload[:username],
          ua: event.payload[:ua]
        }
        add_db_counters!(payload)

        payload.merge!(event.payload[:metadata]) if event.payload[:metadata]

        ::Gitlab::InstrumentationHelper.add_instrumentation_data(payload)

        payload[:queue_duration_s] = event.payload[:queue_duration_s] if event.payload[:queue_duration_s]
        payload[:response] = event.payload[:response] if event.payload[:response]
        payload[:etag_route] = event.payload[:etag_route] if event.payload[:etag_route]
        payload[Labkit::Correlation::CorrelationId::LOG_KEY] = event.payload[Labkit::Correlation::CorrelationId::LOG_KEY] || Labkit::Correlation::CorrelationId.current_id

        if cpu_s = Gitlab::Metrics::System.thread_cpu_duration(::Gitlab::RequestContext.instance.start_thread_cpu_time)
          payload[:cpu_s] = cpu_s.round(2)
        end

        CLOUDFLARE_CUSTOM_HEADERS.each do |_, value|
          payload[value] = event.payload[value] if event.payload[value]
        end

        # https://github.com/roidrage/lograge#logging-errors--exceptions
        exception = event.payload[:exception_object]

        ::Gitlab::ExceptionLogFormatter.format!(exception, payload)

        payload
      end

      def self.add_db_counters!(payload)
        current_transaction = Gitlab::Metrics::Transaction.current
        if current_transaction
          payload[:db_count] = current_transaction.get(:db_count, :counter).to_i
          payload[:db_write_count] = current_transaction.get(:db_write_count, :counter).to_i
          payload[:db_cached_count] = current_transaction.get(:db_cached_count, :counter).to_i
        end
      end
      private_class_method :add_db_counters!
    end
  end
end