require_relative 'ansi_wrapper' require_relative 'ansi_colors' require_relative 'ansi_dimensions' require_relative 'ansi_common' require 'io/console' require 'amazing_print' require 'json' # wraps meanwhile takes care of ansi colors class AnsiFormatter < SemanticLogger::Formatters::Color include AnsiColors CENTER_SIZE = 20 FOREMAN_PREFIX_LENGTH = 18 FAILOVER_WRAP = 80 CHAR_FATAL = '⯶'.freeze TERMINUS_STRING = '╙─╜'.freeze RENDERED_VIEW_DURATION = 100 TOTAL_RENDERED_VIEW_DURATION = RENDERED_VIEW_DURATION * 5 def initialize super(color_map: ColorMap.new( debug: CLEAR + TEXT_GRAY_400, info: CLEAR + TEXT_GRAY_100, warn: CLEAR + BG_YELLOW + TEXT_BLACK, error: CLEAR + BG_RED + TEXT_WHITE, fatal: CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE )) @memory = nil end def call(log, logger) log = alter(log) self.log = log self.logger = logger self.color = color_map[log.level] wrap_level(compute_useful_length, message, payload, exception) end def reject(log) return true if log.name == 'ActionView::Base' && log.message&.starts_with?(' Rendering') true if log.name == 'Rails' && log.message&.starts_with?('Loaded') end private def two_captures_last_as_bold(message, regex) match = message.match(regex) return "unmatched: #{message}" unless match m1, m2 = match.captures "#{m1}#{BOLD}#{m2}#{CLEAR}" end def alter(log) if log.name == 'Rails' if log.message log.message.lstrip! log.message.chomp!('') if log.message.starts_with?('Started') rails = '╓─╖' before = 1 if @memory rails = "╓#{@memory}╖" before = 0 end log.dimensions = AnsiDimensions.new(rails:, before:) @memory = nil log.message = two_captures_last_as_bold(log.message, /(^Started \w* )"(.*?)"/) elsif log.message.starts_with?('Parameters') parameters = log.message.match(/Parameters: ({.*}$)/).match(1) parameters = JSON.parse(parameters.gsub('=>', ':'), symbolize_names: true) parameters = parameters.ai(ruby19_syntax: true, plain: true, multiline: false) parameters = parameters.gsub(/\w*:/) { |key| "#{TEXT_GRAY_200}#{key.chop}#{color_map[:debug]}:" } parameters = parameters.gsub(/: ".*?"/) do |value| ": \"#{TEXT_YELLOW}#{value[3..-2]}#{color_map[:debug]}\"" end log.message = "Parameters: #{parameters}" log.level = :debug elsif log.message.starts_with?('Completed') m1, m2, m3, m4 = log.message.match(/^Completed (\d+) (.*) in (\d+\.?\d*)ms (.*)$/).captures http_code = m1.to_i duration = m3.to_f duration = duration > TOTAL_RENDERED_VIEW_DURATION ? " in #{m3}ms #{m4}" : '' log.message = "Completed #{BOLD}#{http_code}#{CLEAR} #{m2}#{duration}" if http_code / 100 == 2 log.dimensions = AnsiDimensions.new(rails: TERMINUS_STRING, after: 1) elsif http_code / 100 == 3 @memory = '║' log.dimensions = AnsiDimensions.new(rails: "╙#{@memory}╜") elsif http_code / 100 == 4 log.dimensions = AnsiDimensions.new(rails: '╙╨╜') elsif http_code / 100 == 5 log.dimensions = AnsiDimensions.new(rails: "╙#{draw_fatal}╜") end elsif log.message =~ /^(Processing|Parameters)/ log.level = :debug if log.message =~ /^Processing/ log.message = two_captures_last_as_bold(log.message, /(^Processing by \w*#\w* as )(.*)/) end elsif log.message =~ /Redirected/ log.level = :debug log.message = two_captures_last_as_bold(log.message, /^(Redirected to )#{Rails.application.routes.url_helpers.root_url.chop}(.*)/) end elsif log.exception log.dimensions = AnsiDimensions.new( rails: "╓#{draw_fatal(log.level.to_s.chr.upcase)}╖", after: 1, terminus: true ) end elsif log.name =~ /^(ActionView|ActiveRecord)::Base/ log.level = :debug log.message.lstrip! if log.name == 'ActiveRecord::Base' unbold(log.message) if log.message.starts_with?('↳ ') log.message = AnsiCommon.ansi_trace(log.message, '⇄') else sql_match = log.message.match(/\s+\[\[.*\]\]$/) if sql_match sql_command = sql_match.pre_match sql_type, sql_entry = sql_command.split("\e[0m") sql_color_entry = sql_entry.match(AnsiCommon::ANSI_REGEX).to_s sql_args = JSON.parse(sql_match.to_s).map(&:last) sql_args.each_with_index do |value, index| sql_entry.gsub!("$#{index + 1}", colorize(value.inspect, BOLD) + sql_color_entry) end log.message = [sql_type, sql_entry].join(CLEAR) end end elsif log.name == 'ActionView::Base' match = log.message.match(/^Rendered( layout| collection of|) (.*?\.erb)(.*)(\(Duration:.*\))/) if match m1, m2, m3, m4 = match.captures duration = m4.match(/Duration: (\d+\.?\d*)ms/).match(1).to_f duration = duration < RENDERED_VIEW_DURATION ? '' : m4.to_s log.message = "⇤ Rendered#{m1} app/views/#{m2}#{m3}#{duration}" end end end log end def draw_fatal(char = CHAR_FATAL) AnsiColors::BG_MAGENTA + AnsiColors::BOLD + AnsiColors::TEXT_WHITE + char + AnsiColors::CLEAR end def origin = colorize(centerize(log.name), TEXT_CYAN) def build_prefix(char) = "#{origin} ╣#{colorize(char)}╠ " def build_terminus = "#{origin} #{TERMINUS_STRING} " def centerize(text) = text.truncate(CENTER_SIZE).center(CENTER_SIZE) def colorize(text, tint = color) = "#{tint}#{text}#{CLEAR}" def stackisize(items) return '' if items.empty? traces = items.map { |item| AnsiCommon.ansi_trace(item, '➟') } "\n#{traces.join("\n")}" end def build_dimensions(dimensions) "#{origin} #{dimensions.rails} " end def compute_useful_length IO.console.winsize[1] - FOREMAN_PREFIX_LENGTH rescue StandardError FAILOVER_WRAP end def unbold(text) = text.gsub!(BOLD, '') def message colorize(log.message) if log.message end def payload return unless log.payload log.payload.ai(indent: 2, object_id: false) end def exception return unless log.exception exc = log.exception clazz = colorize("#{exc.class}\n", color_map[:fatal]) message = colorize(exc.message.chomp(''), color_map[:error]) backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace)) "#{clazz}#{message}#{backtrace}" 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 = log.dimensions ? build_dimensions(log.dimensions) : build_prefix(level_char) continuation = build_prefix('┆') result = items.map do |item| AnsiWrapper.wrap(item, length, prefix, continuation) end if log.dimensions&.terminus terminus = AnsiWrapper.wrap(' ', length, build_terminus) result << terminus end log.dimensions&.before&.times { result.unshift('') } log.dimensions&.after&.times { result << '' } result.compact.join("\n") end end