summaryrefslogtreecommitdiff
path: root/lib/gitlab/sidekiq_logging/json_formatter.rb
blob: 45c6842c59b20b64260e766ef41d66fbe82ae07a (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

# This is needed for sidekiq-cluster
require 'json'

module Gitlab
  module SidekiqLogging
    class JSONFormatter
      TIMESTAMP_FIELDS = %w[created_at enqueued_at started_at retried_at failed_at completed_at].freeze

      def call(severity, timestamp, progname, data)
        output = {
          severity: severity,
          time: timestamp.utc.iso8601(3)
        }

        case data
        when String
          output[:message] = data
        when Hash
          convert_to_iso8601!(data)
          stringify_args!(data)
          output.merge!(data)
        end

        output.to_json + "\n"
      end

      private

      def convert_to_iso8601!(payload)
        TIMESTAMP_FIELDS.each do |key|
          value = payload[key]
          payload[key] = format_time(value) if value.present?
        end
      end

      def format_time(timestamp)
        return timestamp unless timestamp.is_a?(Numeric)

        Time.at(timestamp).utc.iso8601(3)
      end

      def stringify_args!(payload)
        payload['args'] = Gitlab::Utils::LogLimitedArray.log_limited_array(payload['args'].map(&:to_s)) if payload['args']
      end
    end
  end
end