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.

196 lines
5.8 KiB

3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
2 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
  1. require 'io/console'
  2. require 'amazing_print'
  3. require 'json'
  4. module Semantic
  5. # wraps meanwhile takes care of ansi colors
  6. class AnsiFormatter < SemanticLogger::Formatters::Color
  7. include AnsiColors
  8. TAG_NONE = ''.freeze
  9. CENTER_SIZE = 20
  10. FOREMAN_PREFIX_LENGTH = 18
  11. FAILOVER_WRAP = 80
  12. CHAR_FATAL = '⯶'.freeze
  13. TERMINUS_STRING = '╙─╜'.freeze
  14. RENDERED_VIEW_DURATION = 100
  15. TOTAL_RENDERED_VIEW_DURATION = RENDERED_VIEW_DURATION * 5
  16. def initialize
  17. super(color_map:
  18. ColorMap.new(
  19. debug: CLEAR + TEXT_GRAY_400,
  20. info: CLEAR + TEXT_GRAY_100,
  21. warn: CLEAR + BG_YELLOW + TEXT_BLACK,
  22. error: CLEAR + BG_RED + TEXT_WHITE,
  23. fatal: CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE
  24. ))
  25. @memory = nil
  26. end
  27. def call(log, logger)
  28. # puts 'ok'
  29. log = alter(log)
  30. self.log = log
  31. self.logger = logger
  32. self.color = color_map[log.level]
  33. wrap_level(compute_useful_length, message, payload, exception)
  34. end
  35. def reject(log)
  36. return true if log.name == 'ActionView::Base' && log.message&.starts_with?(' Rendering')
  37. true if log.name == 'Rails' && log.message&.starts_with?('Loaded')
  38. end
  39. private
  40. def tags
  41. first_tag = log.tags.empty? ? TAG_NONE : log.tags.first
  42. colorize(centerize(first_tag, 10), BG_GRAY + DARK_TEXT_YELLOW)
  43. end
  44. def named_tags
  45. return if log.named_tags.empty?
  46. log.named_tags
  47. end
  48. def build_regex_redirected
  49. dev_port = Rails.application.routes.default_url_options[:port]
  50. dev_hosts = ['127.0.0.1', 'localhost', Rails.application.routes.default_url_options[:host]].uniq.join('|')
  51. dev_from = "http://(?:#{dev_hosts}):#{dev_port}"
  52. regex_s = "^(Redirected to )#{dev_from}(.*)"
  53. Regexp.new(regex_s)
  54. end
  55. def ansi_trace(trace, symbol)
  56. match = trace.match(/(↳ )?(.*:\d+)(:in `)?(.*'?)/) # only m2(=file) and m4(=optional function) are useful
  57. return trace unless match
  58. _, m2, _, m4 = match.captures
  59. "#{symbol} #{m2} #{BOLD}#{m4.chop}#{CLEAR}"
  60. end
  61. def two_captures_last_as_bold(message, regex)
  62. match = message.match(regex)
  63. return "unmatched: #{message}" unless match
  64. m1, m2 = match.captures
  65. "#{m1}#{BOLD}#{m2}#{CLEAR}"
  66. end
  67. def alter(log)
  68. if log.name =~ /^(ActionView|ActiveRecord)::Base/
  69. log.level = :debug
  70. log.message.lstrip!
  71. if log.name == 'ActiveRecord::Base'
  72. unbold!(log.message)
  73. if log.message.starts_with?('↳ ')
  74. log.message = ansi_trace(log.message, '⇄')
  75. else
  76. sql_match = log.message.match(/\s+\[\[.*\]\]$/)
  77. if sql_match
  78. sql_command = sql_match.pre_match
  79. sql_type, sql_entry = sql_command.split("\e[0m")
  80. sql_color_entry = sql_entry.match(ANSI_REGEX).to_s
  81. sql_args = JSON.parse(sql_match.to_s).map(&:last)
  82. sql_args.each_with_index do |val, index|
  83. sql_arg = val.inspect
  84. sql_arg = "'#{val.gsub("'", "''")}'" if val.is_a?(String)
  85. sql_entry.gsub!("$#{index + 1}", colorize(sql_arg, BOLD) + sql_color_entry)
  86. end
  87. log.message = [sql_type, sql_entry].join(CLEAR)
  88. end
  89. end
  90. elsif log.name == 'ActionView::Base'
  91. match = log.message.match(/^Rendered( layout| collection of|) (.*?\.erb)(.*)(\(Duration:.*\))/)
  92. if match
  93. m1, m2, m3, m4 = match.captures
  94. duration = m4.match(/Duration: (\d+\.?\d*)ms/).match(1).to_f
  95. duration = duration < RENDERED_VIEW_DURATION ? '' : m4.to_s
  96. log.message = "⇤ Rendered#{m1} app/views/#{m2}#{m3}#{duration}"
  97. end
  98. end
  99. end
  100. log
  101. end
  102. def draw_fatal(char = CHAR_FATAL) = BG_MAGENTA + BOLD + TEXT_WHITE + char + CLEAR
  103. def origin = colorize(centerize(log.name), TEXT_CYAN)
  104. def build_prefix(char) = "#{tags} #{origin}#{colorize(char)}"
  105. def build_terminus = "#{tags} #{origin} #{TERMINUS_STRING} "
  106. def centerize(text, max_length = CENTER_SIZE) = text.reverse.truncate(max_length).reverse.center(max_length)
  107. def stackisize(items)
  108. return '' if items.empty?
  109. traces = items.map { |item| ansi_trace(item, '➟') }
  110. "\n#{traces.join("\n")}"
  111. end
  112. def build_dimensions(dimensions)
  113. "#{tags} #{origin} #{dimensions.rails} "
  114. end
  115. def compute_useful_length
  116. IO.console.winsize[1] - FOREMAN_PREFIX_LENGTH
  117. rescue StandardError
  118. FAILOVER_WRAP
  119. end
  120. def unbold!(text) = text.gsub!(BOLD, '')
  121. def message
  122. colorize(log.message) if log.message
  123. end
  124. def payload
  125. return unless log.payload
  126. log.payload.ai(indent: 2, object_id: false)
  127. end
  128. def exception
  129. return unless log.exception
  130. exc = log.exception
  131. clazz = colorize("#{exc.class}\n", color_map[:fatal])
  132. message = colorize(exc.message.chomp(''), color_map[:error])
  133. backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace))
  134. "#{clazz}#{message}#{backtrace}"
  135. end
  136. def level_char
  137. case log.level
  138. when :info, :debug then ' '
  139. else log.level.to_s.chr.upcase
  140. end
  141. end
  142. def wrap_level(length, *items)
  143. prefix = log.dimensions ? build_dimensions(log.dimensions) : build_prefix(level_char)
  144. continuation = build_prefix('┆')
  145. result = items.map do |item|
  146. Semantic::AnsiWrapper.wrap(item, length, prefix, continuation)
  147. end
  148. if log.dimensions&.terminus
  149. terminus = Semantic::AnsiWrapper.wrap(' ', length, build_terminus)
  150. result << terminus
  151. end
  152. log.dimensions&.before&.times { result.unshift('') }
  153. log.dimensions&.after&.times { result << '' }
  154. result.compact.join("\n")
  155. end
  156. end
  157. end