summaryrefslogtreecommitdiff
path: root/lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb
blob: 045a341f2ed9729fce0cf6a0b7756a8a9750f000 (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
# frozen_string_literal: true

module Gitlab
  module GrapeLogging
    module Formatters
      class LogrageWithTimestamp
        include Gitlab::EncodingHelper

        EMPTY_ARRAY = [].freeze

        def call(severity, datetime, _, data)
          time = data.delete :time
          data[:params] = process_params(data)

          attributes = {
            time: datetime.utc.iso8601(3),
            severity: severity,
            duration: time[:total],
            db: time[:db],
            view: time[:view]
          }.merge!(data)

          ::Lograge.formatter.call(attributes) << "\n"
        end

        private

        def process_params(data)
          return EMPTY_ARRAY unless data.has_key?(:params)

          params_array = data[:params].map { |k, v| { key: k, value: utf8_encode_values(v) } }

          Gitlab::Utils::LogLimitedArray.log_limited_array(params_array, sentinel: Gitlab::Lograge::CustomOptions::LIMITED_ARRAY_SENTINEL)
        end

        def utf8_encode_values(data)
          case data
          when Hash
            data.merge!(data) { |k, v| utf8_encode_values(v) }
          when Array
            data.map! { |v| utf8_encode_values(v) }
          when String
            encode_utf8(data)
          end
        end
      end
    end
  end
end