Class: TTY::Logger::Formatters::JSON

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/logger/formatters/json.rb

Overview

Format data suitable for data exchange

Constant Summary collapse

ELLIPSIS =
"..."

Instance Method Summary collapse

Instance Method Details

#dump(obj, max_bytes: 2**12, max_depth: 3) ⇒ String

Dump data into a JSON formatted string

Parameters:

  • obj (Hash)

    the object to serialize as JSON

Returns:

  • (String)

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tty/logger/formatters/json.rb', line 20

def dump(obj, max_bytes: 2**12, max_depth: 3)
  bytesize = 0

  hash = obj.each_with_object({}) do |(k, v), acc|
    str = (k.to_json + v.to_json)
    items = acc.keys.size - 1

    if bytesize + str.bytesize + items + ELLIPSIS.bytesize > max_bytes
      acc[k] = ELLIPSIS
      break acc
    else
      bytesize += str.bytesize
      acc[k] = dump_val(v, max_depth)
    end
  end
  ::JSON.generate(hash)
end