Class: LogStruct::SemanticLogger::ColorFormatter

Inherits:
SemanticLogger::Formatters::Color
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/log_struct/semantic_logger/color_formatter.rb

Overview

Development-Optimized Colorized JSON Formatter

This formatter extends SemanticLogger's Color formatter to provide beautiful, readable JSON output in development environments. It significantly improves the developer experience when working with structured logs.

Benefits of Colorized Output:

Readability

  • Syntax highlighting: JSON keys, values, and data types are color-coded
  • Visual hierarchy: Different colors help identify structure at a glance
  • Error spotting: Quickly identify malformed data or unexpected values
  • Context separation: Log entries are visually distinct from each other

Performance in Development

  • Faster debugging: Quickly scan logs without reading every character
  • Pattern recognition: Colors help identify common log patterns
  • Reduced cognitive load: Less mental effort required to parse log output
  • Improved workflow: Spend less time reading logs, more time coding

Customization

  • Configurable colors: Customize colors for keys, strings, numbers, etc.
  • Environment-aware: Automatically disabled in production/CI environments
  • Fallback support: Gracefully falls back to standard formatting if needed

Color Mapping:

  • Keys: Yellow - Easy to spot field names
  • Strings: Green - Clear indication of text values
  • Numbers: Blue - Numeric values stand out
  • Booleans: Magenta - true/false values are distinctive
  • Null: Red - Missing values are immediately visible
  • Logger names: Cyan - Source identification

Integration with SemanticLogger:

This formatter preserves all SemanticLogger benefits (performance, threading, reliability) while adding visual enhancements. It processes LogStruct types, hashes, and plain messages with appropriate colorization.

The formatter is automatically enabled in development when enable_color_output is true (default), providing zero-configuration enhanced logging experience.

Instance Method Summary collapse

Constructor Details

#initialize(color_map: nil, **args) ⇒ void

Parameters:

  • color_map (Hash{Symbol => Symbol}, nil) (defaults to: nil)
  • args (T.untyped)


53
54
55
56
57
58
59
# File 'lib/log_struct/semantic_logger/color_formatter.rb', line 53

def initialize(color_map: nil, **args)
  super(**args)
  @logstruct_formatter = T.let(LogStruct::Formatter.new, LogStruct::Formatter)

  # Set up custom color mapping
  @custom_colors = T.let(color_map || default_color_map, T::Hash[Symbol, Symbol])
end

Instance Method Details

#call(log, logger) ⇒ String

Parameters:

  • log (::SemanticLogger::Log)
  • logger (T.untyped)

Returns:

  • (String)


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/log_struct/semantic_logger/color_formatter.rb', line 62

def call(log, logger)
  # Handle LogStruct types specially with colorization
  if log.payload.is_a?(LogStruct::Log::Interfaces::CommonFields)
    # Get the LogStruct formatted JSON
    logstruct_json = @logstruct_formatter.call(log.level, log.time, log.name, log.payload)

    # Parse and colorize it
    begin
      parsed_data = T.let(JSON.parse(logstruct_json), T::Hash[String, T.untyped])
      colorized_json = colorize_json(parsed_data)

      # Use SemanticLogger's prefix formatting but with our colorized content
      prefix = format("%<time>s %<level>s [%<process>s] %<name>s -- ",
        time: format_time(log.time),
        level: format_level(log.level),
        process: log.process_info,
        name: format_name(log.name))

      "#{prefix}#{colorized_json}\n"
    rescue JSON::ParserError
      # Fallback to standard formatting
      super
    end
  elsif log.payload.is_a?(Hash) || log.payload.is_a?(T::Struct)
    # Process hashes through our formatter then colorize
    begin
      logstruct_json = @logstruct_formatter.call(log.level, log.time, log.name, log.payload)
      parsed_data = T.let(JSON.parse(logstruct_json), T::Hash[String, T.untyped])
      colorized_json = colorize_json(parsed_data)

      prefix = format("%<time>s %<level>s [%<process>s] %<name>s -- ",
        time: format_time(log.time),
        level: format_level(log.level),
        process: log.process_info,
        name: format_name(log.name))

      "#{prefix}#{colorized_json}\n"
    rescue JSON::ParserError
      # Fallback to standard formatting
      super
    end
  else
    # For plain messages, use SemanticLogger's default colorization
    super
  end
end