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.

77 lines
1.9 KiB

6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
  1. require_relative 'ansi_wrapper'
  2. require_relative 'ansi_colors'
  3. require 'io/console'
  4. require 'amazing_print'
  5. require 'json'
  6. # wraps meanwhile takes care of ansi colors
  7. class AnsiFormatter < SemanticLogger::Formatters::Color
  8. include AnsiColors
  9. ANSI_DEBUG = CLEAR + TEXT_GRAY_400
  10. ANSI_INFO = CLEAR + TEXT_GRAY_100
  11. ANSI_WARN = CLEAR + BG_YELLOW + TEXT_BLACK
  12. ANSI_ERROR = CLEAR + BG_RED + TEXT_WHITE
  13. ANSI_FATAL = CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE
  14. NAME_MAX_SIZE = 20
  15. def initialize
  16. super(color_map: ColorMap.new(
  17. debug: ANSI_DEBUG,
  18. info: ANSI_INFO,
  19. warn: ANSI_WARN,
  20. error: ANSI_ERROR,
  21. fatal: ANSI_FATAL
  22. ))
  23. end
  24. def call(log, logger)
  25. self.log = log
  26. self.logger = logger
  27. self.color = color_map[log.level]
  28. wrap_level(level, message, payload, exception)
  29. end
  30. def origin
  31. origin = log.name.truncate(NAME_MAX_SIZE).center(NAME_MAX_SIZE)
  32. colorize(origin, AnsiColors::TEXT_CYAN)
  33. end
  34. def message
  35. return unless log.message
  36. colorize(log.message)
  37. end
  38. def exception
  39. return unless log.exception
  40. clazz = "#{log.exception.class}\n"
  41. message = log.exception.message.chomp('')
  42. backtrace = clean_backtrace(log.exception.backtrace)
  43. "#{colorize(clazz, ANSI_FATAL)}#{colorize(message, ANSI_ERROR)}#{backtrace}"
  44. end
  45. private
  46. def clean_backtrace(backtrace)
  47. root_path = Rails.root.to_s
  48. backtrace = backtrace.select { |line| line.starts_with?(root_path) }
  49. backtrace = backtrace.map { |line| line.delete_prefix("#{root_path}/") }
  50. backtrace.compact.join("\n")
  51. end
  52. def colorize(text, tint = color)
  53. "#{tint}#{text}#{AnsiColors::CLEAR}"
  54. end
  55. def wrap_level(level, *items)
  56. prefix = "#{origin} #{colorize('>')} "
  57. continuation = "#{origin} #{colorize('#')} "
  58. items.map do |item|
  59. AnsiWrapper.wrap(item, 100, prefix, continuation)
  60. end.compact.join("\n") # FIXME: previously was: join(' ')
  61. end
  62. end