You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

94 lines
2.4 KiB

require_relative 'ansi_wrapper'
require_relative 'ansi_colors'
require 'io/console'
require 'amazing_print'
require 'json'
# wraps meanwhile takes care of ansi colors
class AnsiFormatter < SemanticLogger::Formatters::Color
include AnsiColors
ANSI_DEBUG = CLEAR + TEXT_GRAY_400
ANSI_INFO = CLEAR + TEXT_GRAY_100
ANSI_WARN = CLEAR + BG_YELLOW + TEXT_BLACK
ANSI_ERROR = CLEAR + BG_RED + TEXT_WHITE
ANSI_FATAL = CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE
NAME_MAX_SIZE = 20
FOREMAN_PREFIX_LENGTH = 18
DEFAULT_UNDETECTED_WRAP = 80
def initialize
super(color_map: ColorMap.new(
debug: ANSI_DEBUG,
info: ANSI_INFO,
warn: ANSI_WARN,
error: ANSI_ERROR,
fatal: ANSI_FATAL
))
end
def call(log, logger)
self.log = log
self.logger = logger
self.color = color_map[log.level]
wrap_length = compute_useful_length
wrap_level(wrap_length, message, payload, exception)
end
def origin
origin = log.name.truncate(NAME_MAX_SIZE).center(NAME_MAX_SIZE)
colorize(origin, AnsiColors::TEXT_CYAN)
end
def message
return unless log.message
colorize(log.message)
end
def exception
return unless log.exception
clazz = "#{log.exception.class}\n"
message = log.exception.message.chomp('')
backtrace = clean_backtrace(log.exception.backtrace)
"#{colorize(clazz, ANSI_FATAL)}#{colorize(message, ANSI_ERROR)}#{backtrace}"
end
private
def colorize(text, tint = color) = "#{tint}#{text}#{AnsiColors::CLEAR}"
def build_prefix = "#{origin} #{colorize(draw_rails(level_char))} "
def build_continuation = "#{origin} #{colorize(draw_rails('┆'))} "
def draw_rails(char) = "#{char}"
def compute_useful_length
IO.console.winsize[1] - FOREMAN_PREFIX_LENGTH
rescue StandardError
DEFAULT_UNDETECTED_WRAP
end
def clean_backtrace(backtrace)
root_path = Rails.root.to_s
backtrace = backtrace.select { |line| line.starts_with?(root_path) }
backtrace = backtrace.map { |line| line.delete_prefix("#{root_path}/") }
backtrace.compact.join("\n")
end
def level_char
case log.level
when :info, :debug then ' '
else log.level.to_s.chr.upcase
end
end
def wrap_level(length, *items)
prefix = build_prefix
continuation = build_continuation
items.map do |item|
AnsiWrapper.wrap(item, length, prefix, continuation)
end.compact.join("\n")
end
end