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.

80 lines
2.4 KiB

10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
  1. # Opinioned Rails custom formatter
  2. class BasicFormatter < SemanticLogger::Formatters::Color
  3. NAME_MAX_SIZE = 25
  4. CONTENT_PREFIX = ' '.freeze
  5. ANSI_DEBUG = "\e[90m".freeze
  6. ANSI_INFO = SemanticLogger::AnsiColors::GREEN
  7. ANSI_WARN = SemanticLogger::AnsiColors::YELLOW
  8. ANSI_ERROR = SemanticLogger::AnsiColors::RED
  9. ANSI_FATAL = SemanticLogger::AnsiColors::MAGENTA
  10. ANSI_NEUTRAL_INFO = SemanticLogger::AnsiColors::WHITE
  11. ANSI_REVERSED_WARNING = "\e[0;30;43m".freeze
  12. ANSI_REVERSED_ERROR = "\e[1;30;41m".freeze
  13. ANSI_REVERSED_FATAL = "\e[1;30;41m".freeze
  14. CONTENT_COLOR_MAP = ColorMap.new(
  15. debug: ANSI_DEBUG,
  16. info: ANSI_NEUTRAL_INFO,
  17. warn: ANSI_REVERSED_WARNING,
  18. error: ANSI_REVERSED_ERROR,
  19. fatal: ANSI_REVERSED_FATAL
  20. )
  21. def initialize
  22. super(color_map: ColorMap.new(
  23. debug: ANSI_DEBUG,
  24. info: ANSI_INFO,
  25. warn: ANSI_WARN,
  26. error: ANSI_ERROR,
  27. fatal: ANSI_ERROR
  28. ))
  29. end
  30. def message
  31. return unless log.message
  32. message = log.message
  33. if log.name == 'Rails' && message.starts_with?('Completed')
  34. message.rstrip!
  35. message += "\n" unless message.starts_with?('Completed 5')
  36. end
  37. "#{CONTENT_PREFIX}#{CONTENT_COLOR_MAP[log.level]}#{message}#{color_map.clear}"
  38. end
  39. def level
  40. level = log.level == :info ? ' ' : log.level.to_s.chr.upcase
  41. "#{color}#{level}#{color_map.clear}"
  42. end
  43. def name
  44. "#{ANSI_DEBUG}#{log.name.truncate(NAME_MAX_SIZE).center(NAME_MAX_SIZE)}#{color_map.clear}"
  45. end
  46. def exception # rubocop:disable Metrics/AbcSize
  47. return unless log.exception
  48. root_path = Rails.root.to_s
  49. stack = log.exception.backtrace.select { |line| line.starts_with?(root_path) }
  50. stack = stack.map { |line| line.delete_prefix("#{root_path}/") }
  51. "#{CONTENT_PREFIX}#{ANSI_REVERSED_ERROR}#{log.exception.class}#{color_map.clear}: #{color}#{log.exception.message}#{color_map.clear}#{backtrace(stack)}" # rubocop:disable Layout/LineLength
  52. end
  53. def call(log, logger)
  54. self.color = color_map[log.level]
  55. self.log = log
  56. self.logger = logger
  57. [name, level, tags, named_tags, duration, message, payload, exception].compact.join(' ')
  58. end
  59. private
  60. def backtrace(stack)
  61. nil unless stack.count.positive?
  62. prefix = [name, level, tags, named_tags, duration, message, payload, CONTENT_PREFIX].compact.join(' ')
  63. "\n#{prefix}#{ANSI_ERROR}#{stack.join("\n#{prefix}#{ANSI_ERROR}")}#{color_map.clear}"
  64. end
  65. end