Class: Betterlog::Log::EventFormatter

Inherits:
Object
  • Object
show all
Includes:
ComplexConfig::Provider::Shortcuts, Term::ANSIColor
Defined in:
lib/betterlog/log/event_formatter.rb

Overview

Formats log events for structured logging output.

This class provides functionality to format log events into various output formats, including JSON representation and pretty-printed strings with color support. It handles the conversion of log data into human-readable formats while maintaining structured logging capabilities.

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(event) ⇒ Betterlog::Log::EventFormatter

Initializes a new EventFormatter instance with the given log event.

This constructor sets up the formatter with a specific log event to be formatted, preparing it for subsequent formatting operations such as JSON generation or pretty printing with color support.

this instance

Parameters:



28
29
30
# File 'lib/betterlog/log/event_formatter.rb', line 28

def initialize(event)
  @event = event
end

Instance Method Details

#format(pretty: false, color: false, format: :default) ⇒ String

Formats the log event according to specified options.

This method processes a log event and returns either a JSON representation or a formatted string based on the provided formatting options. It supports pretty printing with custom format patterns and optional colorization.

Parameters:

  • pretty (Boolean, Symbol) (defaults to: false)

    when true, enables pretty printing; when :format, uses a specific format pattern; otherwise uses JSON generation

  • color (Boolean) (defaults to: false)

    whether to apply color formatting to the output

  • format (Symbol) (defaults to: :default)

    the format identifier to use for pretty printing

Returns:

  • (String)

    the formatted log event as a string

See Also:

  • #format_pattern
  • JSON.generate


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/betterlog/log/event_formatter.rb', line 48

def format(pretty: false, color: false, format: :default)
  old_coloring, Term::ANSIColor.coloring = Term::ANSIColor.coloring?, color
  f = cc.log.formats[format] and format = f
  case pretty
  when :format
    format_pattern(format: format)
  else
    JSON.generate(@event)
  end
ensure
  Term::ANSIColor.coloring = old_coloring
end