Class: NextStation::Logging::Formatter::Json
- Inherits:
-
Logger::Formatter
- Object
- Logger::Formatter
- NextStation::Logging::Formatter::Json
- 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
-
#call(severity, time, _progname, msg) ⇒ String
Formats the log entry into a JSON string.
Instance Method Details
#call(severity, time, _progname, msg) ⇒ String
Formats the log entry into a JSON string.
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 |