summaryrefslogtreecommitdiff
path: root/lib/gitlab/utils/log_limited_array.rb
blob: 9c207758580a7eb61e57e3ca03ce77728359f527 (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
# frozen_string_literal: true

module Gitlab
  module Utils
    module LogLimitedArray
      MAXIMUM_ARRAY_LENGTH = 10.kilobytes

      # Prepare an array for logging by limiting its JSON representation
      # to around 10 kilobytes. Once we hit the limit, add the sentinel
      # value as the last item in the returned array.
      def self.log_limited_array(array, sentinel: '...')
        return [] unless array.is_a?(Array)

        total_length = 0
        limited_array = array.take_while do |arg|
          total_length += arg.to_json.length

          total_length <= MAXIMUM_ARRAY_LENGTH
        end

        limited_array.push(sentinel) if total_length > MAXIMUM_ARRAY_LENGTH

        limited_array
      end
    end
  end
end