Class: Browserctl::JsonlFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/browserctl/logger.rb

Overview

Formats every log line as a single JSON object: level, component, msg, …. If the message is a Hash, its keys are merged so callers can attach structured context, e.g. ‘logger.info(event: “x”, session: id)`.

Instance Method Summary collapse

Constructor Details

#initialize(component:) ⇒ JsonlFormatter

Returns a new instance of JsonlFormatter.



49
50
51
# File 'lib/browserctl/logger.rb', line 49

def initialize(component:)
  @component = component
end

Instance Method Details

#call(severity, time, _progname, msg) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/browserctl/logger.rb', line 53

def call(severity, time, _progname, msg)
  record = {
    ts: time.utc.iso8601(3),
    level: severity,
    component: @component
  }

  case msg
  when Hash
    explicit = msg[:msg] || msg["msg"]
    record[:msg] = explicit if explicit
    record.merge!(msg.reject { |k, _| k.to_s == "msg" })
  when Exception
    record[:msg] = "#{msg.class}: #{msg.message}"
    record[:backtrace] = Array(msg.backtrace).first(10)
  else
    record[:msg] = msg.to_s
  end

  "#{JSON.generate(record)}\n"
end