Class: Sonnet::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/sonnet/formatter.rb

Constant Summary collapse

TIMESTAMP_FORMAT =
"%FT%T.%LZ"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(severity, time, progname, data) ⇒ Formatter

Returns a new instance of Formatter.



13
14
15
16
17
18
# File 'lib/sonnet/formatter.rb', line 13

def initialize(severity, time, progname, data)
  @severity = severity
  @time = time
  @progname = progname
  @data = data
end

Class Method Details

.call(severity, time, progname, data) ⇒ Object



9
10
11
# File 'lib/sonnet/formatter.rb', line 9

def self.call(severity, time, progname, data)
  new(severity, time, progname, data).to_json
end

Instance Method Details

#as_jsonObject



55
56
57
58
59
60
61
62
63
# File 'lib/sonnet/formatter.rb', line 55

def as_json
  {
    program: program,
    # hostname: hostname,
    level: level,
    timestamp: timestamp,
    pid: pid
  }.merge(data).compact
end

#dataObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/sonnet/formatter.rb', line 28

def data
  case @data
  when Exception
    Serializer.serialize_exception(@data)
  when Hash
    @data
  else
    serialize_string(@data)
  end
end

#levelObject



39
40
41
# File 'lib/sonnet/formatter.rb', line 39

def level
  @severity&.downcase
end

#pidObject



51
52
53
# File 'lib/sonnet/formatter.rb', line 51

def pid
  $$
end

#programObject



20
21
22
# File 'lib/sonnet/formatter.rb', line 20

def program
  @progname || File.basename($0)
end

#serialize_string(string) ⇒ Object

def hostname

@hostname || Socket.gethostname.force_encoding('UTF-8')

end



47
48
49
# File 'lib/sonnet/formatter.rb', line 47

def serialize_string(string)
  { message: string.to_s }
end

#timestampObject



24
25
26
# File 'lib/sonnet/formatter.rb', line 24

def timestamp
  (@time || Time.now).utc.strftime(TIMESTAMP_FORMAT)
end

#to_jsonObject



65
66
67
# File 'lib/sonnet/formatter.rb', line 65

def to_json
  as_json.to_json + "\n"
end