Class: Pgbus::LogFormatter::JSON

Inherits:
Logger::Formatter
  • Object
show all
Defined in:
lib/pgbus/log_formatter.rb

Overview

JSON formatter for structured logging. Each log line is a single JSON object followed by a newline. Extracts the [Pgbus::Component] prefix from messages into a separate “component” field.

Output fields:

ts  — ISO 8601 timestamp with milliseconds
pid — process ID
tid — thread ID (short hex)
lvl — severity (DEBUG/INFO/WARN/ERROR/FATAL)
msg — the log message (with component prefix stripped)
component — extracted from [Pgbus] or [Pgbus::Foo] prefix (optional)
ctx — thread-local context hash (optional, only when non-empty)

Constant Summary collapse

COMPONENT_PREFIX =
/\A\[([^\]]+)\]\s*/

Instance Method Summary collapse

Instance Method Details

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



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/pgbus/log_formatter.rb', line 73

def call(severity, time, _progname, message)
  msg = message.to_s
  hash = {
    ts: time.utc.iso8601(3),
    pid: ::Process.pid,
    tid: LogFormatter.tid,
    lvl: severity
  }

  if (match = msg.match(COMPONENT_PREFIX))
    hash[:component] = match[1]
    msg = msg.sub(COMPONENT_PREFIX, "")
  end

  hash[:msg] = msg

  ctx = LogFormatter.current_context
  hash[:ctx] = ctx unless ctx.empty?

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