Method: Betterlog::Log::Event#to_json

Defined in:
lib/betterlog/log/event.rb

#to_json(*a) ⇒ String

Converts the log event to a JSON string representation.

This method generates a JSON-encoded string of the log event’s data, providing a structured format suitable for logging and transmission. In cases where JSON generation fails due to encoding issues or other errors, it falls back to a minimal JSON representation containing only the severity and a cleaned-up message to ensure logging functionality remains intact.

Returns:

  • (String)

    A JSON string representation of the log event

See Also:



131
132
133
134
135
136
137
138
139
140
141
# File 'lib/betterlog/log/event.rb', line 131

def to_json(*a)
  JSON.generate(as_json)
rescue
  # Sometimes rails logging messages contain invalid utf-8 characters
  # generating various standard errors. Let's fallback to a barebones
  # event with just a cleaned up message for these cases.
  JSON.generate({
    severity: @data[:severity],
    message: @data.fetch(:message, '').encode('utf-8', invalid: :replace, undef: :replace, replace: ''),
  })
end