Class: NextStation::Logging::Formatter::Json

Inherits:
Logger::Formatter
  • Object
show all
Defined in:
lib/next_station/logging/formatters/json.rb

Overview

A custom logger formatter that outputs log entries as JSON objects.

This formatter is designed to work with the standard ‘Logger` class. It structures log messages into a JSON format that includes severity, timestamp, process ID, and structured data from the operation. It also automatically includes OpenTelemetry trace and span IDs if the `opentelemetry-sdk` is present.

Constant Summary collapse

OTEL_AVAILABLE =

Avoid repeated defined? calls in a hot path

defined?(::OpenTelemetry::Trace)

Instance Method Summary collapse

Instance Method Details

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

Formats the log entry into a JSON string.

Parameters:

  • severity (String)

    The log severity (e.g., ‘INFO’, ‘WARN’).

  • time (Time)

    The timestamp of the log event.

  • _progname (String)

    The program name (unused).

  • msg (String, Hash)

    The log message. If a Hash, it is treated as structured data with keys like ‘:message`, `:payload`, and `:operation`. If a String, it becomes the value of the `:message` key.

Returns:

  • (String)

    The formatted log entry as a JSON string, terminated with a newline character.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/next_station/logging/formatters/json.rb', line 29

def call(severity, time, _progname, msg)
  data = msg.is_a?(Hash) ? msg : { message: msg.to_s }

  log_entry = {
    level: severity,
    time: time.utc.strftime('%Y-%m-%dT%H:%M:%S.%6N'),
    pid: Process.pid,
    origin: build_origin(data),
    message: data[:message]
  }

  add_payload_to_log_entry(log_entry, data) if data[:payload]

  add_otel_context(log_entry) if OTEL_AVAILABLE

  # Compact the hash to remove nil values and ensure a newline
  JSON.generate(log_entry.compact) << "\n"
end