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.

78 lines
2.3 KiB

3 weeks ago
  1. module Semantic
  2. # Abstract colorized formatter
  3. class AbstractFormatter < SemanticLogger::Formatters::Color
  4. include AnsiColors
  5. TAG_NONE = ''.freeze
  6. CENTER_SIZE = 20
  7. TAG_FIXED_LENGTH = Rails.application.config.x.action_controller.main_session_tag_fixed_length || 10
  8. def initialize(time_format: nil)
  9. super(color_map: ColorMap.new(
  10. debug: CLEAR + TEXT_GRAY_400,
  11. info: CLEAR + TEXT_GRAY_100,
  12. warn: CLEAR + BG_YELLOW + TEXT_BLACK,
  13. error: CLEAR + DARK_BG_RED + TEXT_WHITE,
  14. fatal: CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE
  15. ))
  16. @time_format = time_format
  17. end
  18. private
  19. def exception
  20. return unless log.exception
  21. if log.exception.is_a?(Semantic::TagWrapError)
  22. exc_wrapper = log.exception
  23. # puts "TAG_WRAP detected #{exc_wrapper.tag}"
  24. exc = exc_wrapper.error
  25. log.tags = Array.wrap(exc_wrapper.tag)
  26. else
  27. exc = log.exception
  28. end
  29. clazz = colorize("#{exc.class}\n", color_map[:fatal])
  30. message = colorize(exc.message.chomp(''), color_map[:error])
  31. # TODO: backtrace_cleaner might be optionally disable from Live::Constant
  32. backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace))
  33. "#{clazz}#{message}#{backtrace}"
  34. end
  35. def origin
  36. true_class = log.name == log.name.upcase_first
  37. taint = true_class ? TEXT_CYAN : TEXT_GRAY_400
  38. colorize(centerize(log.name), taint)
  39. end
  40. def ansi_trace(trace, symbol)
  41. match = trace.match(/(↳ )?(.*:\d+)(:in `)?(.*'?)/) # only m2(=file) and m4(=optional function) are useful
  42. return trace unless match
  43. _, m2, _, m4 = match.captures
  44. "#{symbol} #{m2} #{BOLD}#{m4.chop}#{CLEAR}"
  45. end
  46. def stackisize(items)
  47. return '' if items.empty?
  48. traces = items.map { |item| ansi_trace(item, '➟') }
  49. "\n#{traces.join("\n")}"
  50. end
  51. def tags
  52. first_tag, taint = log.tags.empty? ? [TAG_NONE, CLEAR] : [log.tags.first, BG_GRAY + TEXT_YELLOW]
  53. colorize(centerize(first_tag, TAG_FIXED_LENGTH), taint)
  54. end
  55. def named_tags
  56. return if log.named_tags.empty?
  57. log.named_tags
  58. end
  59. def centerize(text, max_length = CENTER_SIZE) = text.reverse.truncate(max_length).reverse.center(max_length)
  60. end
  61. end