Class: Makit::Logging::Formatters::JsonFormatter

Inherits:
Base
  • Object
show all
Defined in:
lib/makit/logging/formatters/json_formatter.rb

Overview

JSON formatter for structured logging

Formats log requests as JSON objects with timestamp, level, message, and context. This is ideal for log aggregation systems and structured data analysis.

Examples:

formatter = JsonFormatter.new
formatted = formatter.format(log_request)
# => '{"timestamp":"2024-01-15T10:30:45Z","level":"INFO","message":"User logged in","context":{"user_id":123}}'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options: {}) ⇒ JsonFormatter

Initialize JSON formatter

Parameters:

  • options (Hash) (defaults to: {})

    JSON generation options



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/makit/logging/formatters/json_formatter.rb', line 25

def initialize(options: {})
  @options = {
    indent: nil,
    space: nil,
    space_before: nil,
    object_nl: nil,
    array_nl: nil,
    allow_nan: false,
    max_nesting: 100,
  }.merge(options)
end

Instance Attribute Details

#optionsHash (readonly)

Returns additional options for JSON formatting.

Returns:

  • (Hash)

    additional options for JSON formatting



20
21
22
# File 'lib/makit/logging/formatters/json_formatter.rb', line 20

def options
  @options
end

Instance Method Details

#configHash

Get formatter configuration

Returns:

  • (Hash)

    formatter configuration including JSON options



57
58
59
60
61
# File 'lib/makit/logging/formatters/json_formatter.rb', line 57

def config
  super.merge(
    json_options: @options,
  )
end

#format(log_request) ⇒ String

Format log request as JSON

Parameters:

  • log_request (LogRequest)

    the log request to format

Returns:

  • (String)

    JSON formatted log entry



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/makit/logging/formatters/json_formatter.rb', line 41

def format(log_request)
  log_data = {
    timestamp: log_request.timestamp.iso8601,
    level: log_request.level.to_s.upcase,
    message: log_request.message,
  }

  # Add context if present

  log_data[:context] = log_request.context unless log_request.context.empty?

  JSON.generate(log_data, @options)
end