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.

82 lines
2.6 KiB

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