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.

72 lines
2.0 KiB

2 months ago
2 months 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(color_map:, time_format: nil)
  9. super(color_map:)
  10. @time_format = time_format
  11. end
  12. private
  13. def exception
  14. return unless log.exception
  15. if log.exception.is_a?(Semantic::TagWrapError)
  16. exc_wrapper = log.exception
  17. # puts "TAG_WRAP detected #{exc_wrapper.tag}"
  18. exc = exc_wrapper.error
  19. log.tags = Array.wrap(exc_wrapper.tag)
  20. else
  21. exc = log.exception
  22. end
  23. clazz = colorize("#{exc.class}\n", color_map[:fatal])
  24. message = colorize(exc.message.chomp(''), color_map[:error])
  25. # TODO: backtrace_cleaner might be optionally disable from Live::Constant
  26. backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace))
  27. "#{clazz}#{message}#{backtrace}"
  28. end
  29. def origin
  30. true_class = log.name == log.name.upcase_first
  31. taint = true_class ? TEXT_CYAN : TEXT_GRAY_400
  32. colorize(centerize(log.name), taint)
  33. end
  34. def ansi_trace(trace, symbol)
  35. match = trace.match(/(↳ )?(.*:\d+)(:in `)?(.*'?)/) # only m2(=file) and m4(=optional function) are useful
  36. return trace unless match
  37. _, m2, _, m4 = match.captures
  38. "#{symbol} #{m2} #{BOLD}#{m4.chop}#{CLEAR}"
  39. end
  40. def stackisize(items)
  41. return '' if items.empty?
  42. traces = items.map { |item| ansi_trace(item, '➟') }
  43. "\n#{traces.join("\n")}"
  44. end
  45. def tags
  46. first_tag, taint = log.tags.empty? ? [TAG_NONE, CLEAR] : [log.tags.first, BG_GRAY + TEXT_YELLOW]
  47. colorize(centerize(first_tag, TAG_FIXED_LENGTH), taint)
  48. end
  49. def named_tags
  50. return if log.named_tags.empty?
  51. log.named_tags
  52. end
  53. def centerize(text, max_length = CENTER_SIZE) = text.reverse.truncate(max_length).reverse.center(max_length)
  54. end
  55. end