class Semlogr::Sinks::ColoredConsole

Constants

COLOR_CODES
DEFAULT_TEMPLATE
LOG_SEVERITY_COLORS

Public Class Methods

new(template: DEFAULT_TEMPLATE) click to toggle source
# File lib/semlogr/sinks/colored_console.rb, line 26
def initialize(template: DEFAULT_TEMPLATE)
  @template = Templates::Parser.parse(template)
end

Public Instance Methods

emit(log_event) click to toggle source
# File lib/semlogr/sinks/colored_console.rb, line 30
def emit(log_event)
  output = +''
  output_properties = Properties::OutputProperties.create(log_event)

  @template.tokens.each do |token|
    case token
    when Templates::PropertyToken
      render_property_token(output, token, log_event, output_properties)
    else
      token.render(output, output_properties)
    end
  end

  STDOUT.write(output)
end

Private Instance Methods

colorize(output, color) { || ... } click to toggle source
# File lib/semlogr/sinks/colored_console.rb, line 82
def colorize(output, color)
  color ||= :white

  output << "\e[#{COLOR_CODES[color]}m"
  yield
  output << "\e[0m"
end
render_message(output, log_event) click to toggle source
# File lib/semlogr/sinks/colored_console.rb, line 69
def render_message(output, log_event)
  log_event.template.tokens.each do |token|
    case token
    when Templates::PropertyToken
      colorize(output, :blue) do
        token.render(output, log_event.properties)
      end
    else
      token.render(output, log_event.properties)
    end
  end
end
render_property_token(output, token, log_event, output_properties) click to toggle source
# File lib/semlogr/sinks/colored_console.rb, line 48
def render_property_token(output, token, log_event, output_properties)
  case token.property_name
  when :message
    render_message(output, log_event)
  when :severity
    colorize(output, LOG_SEVERITY_COLORS[log_event.severity]) do
      token.render(output, output_properties)
    end
  when :error
    return unless output_properties[:error]

    colorize(output, LOG_SEVERITY_COLORS[log_event.severity]) do
      token.render(output, output_properties)
    end
  else
    return unless output_properties[token.property_name]

    token.render(output, output_properties)
  end
end