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.

84 lines
2.7 KiB

2 months ago
  1. module Semantic
  2. # My Custom colorized formatter
  3. class BasicFormatter < SemanticLogger::Formatters::Color
  4. ANSI_REVERSED_WARNING = "\e[0;30;43m".freeze
  5. ANSI_REVERSED_ERROR = "\e[1;30;41m".freeze
  6. ANSI_GRAY = "\e[90m".freeze
  7. # Return the complete log level name in uppercase
  8. def initialize
  9. super(time_format: '%H:%M:%S',
  10. color_map: ColorMap.new(
  11. debug: ANSI_GRAY,
  12. info: SemanticLogger::AnsiColors::GREEN,
  13. warn: SemanticLogger::AnsiColors::YELLOW
  14. ))
  15. @time_format = nil if File.exist?(File.join(Rails.root, 'Procfile.dev'))
  16. end
  17. def time
  18. "#{color}#{format_time(log.time)}#{color_map.clear}" if time_format
  19. end
  20. def message
  21. return unless log.message
  22. prefix = "#{color}--#{color_map.clear}"
  23. case log.level
  24. when :info
  25. message = log.message
  26. message = message&.rstrip if log.name == 'Rails' && message.starts_with?('Completed')
  27. if log.name == 'Rails' && message.starts_with?('Started')
  28. message = message.split('for')[0]
  29. puts '' if Rails.env.development?
  30. end
  31. if log.name == 'Rails' || log.name == 'ActionView::Base'
  32. "#{prefix} #{ANSI_GRAY}#{message}#{color_map.clear}"
  33. else
  34. "#{prefix} #{SemanticLogger::AnsiColors::WHITE}#{message}#{color_map.clear}"
  35. end
  36. when :warn
  37. "#{prefix} #{ANSI_REVERSED_WARNING}#{log.message}#{color_map.clear}"
  38. when :error, :fatal
  39. "#{prefix} #{ANSI_REVERSED_ERROR}#{log.message}#{color_map.clear}"
  40. else
  41. "#{prefix} #{color}#{log.message}#{color_map.clear}"
  42. end
  43. end
  44. def tags; end
  45. def process_info
  46. fname = file_name_and_line
  47. "#{color}[#{fname}]#{color_map.clear}" if fname
  48. end
  49. def exception
  50. return unless log.exception
  51. root_path = Rails.root.to_s
  52. backtrace = log.exception.backtrace.select do |line|
  53. line.starts_with?(root_path)
  54. end
  55. if backtrace.count.positive?
  56. "-- #{ANSI_REVERSED_ERROR}#{log.exception.class}#{color_map.clear} #{color}#{log.exception.message}#{color_map.clear}#{SemanticLogger::AnsiColors::WHITE}\n\t#{backtrace.join("\n\t")}#{color_map.clear}\n\n"
  57. else
  58. "-- #{ANSI_REVERSED_ERROR}#{log.exception.class}: #{log.exception.message}#{color_map.clear}\n\n"
  59. end
  60. end
  61. def call(log, logger)
  62. self.color = color_map[log.level]
  63. self.log = log
  64. self.logger = logger
  65. if @time_format
  66. [time, level, process_info, tags, named_tags, duration, name, message, payload, exception].compact.join(' ')
  67. else
  68. [tags, named_tags, duration, name, message, payload, exception].compact.join(' ')
  69. end
  70. end
  71. end
  72. end