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.

213 lines
6.3 KiB

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
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
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 FancyFormatter < 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 'ok2'
  29. log = alter(log)
  30. self.log = log
  31. self.logger = logger
  32. self.color = color_map[log.level]
  33. computed_exception = exception
  34. result = wrap_level(compute_useful_length, message, payload, computed_exception)
  35. return result unless computed_exception
  36. result << "\n" << build_terminus
  37. end
  38. def reject(log)
  39. return true if log.name == 'ActionView::Base' && log.message&.starts_with?(' Rendering')
  40. true if log.name == 'Rails' && log.message&.starts_with?('Loaded')
  41. end
  42. private
  43. def tags
  44. first_tag = log.tags.empty? ? TAG_NONE : log.tags.first
  45. colorize(centerize(first_tag, 10), BG_GRAY + DARK_TEXT_YELLOW)
  46. end
  47. def named_tags
  48. return if log.named_tags.empty?
  49. log.named_tags
  50. end
  51. def build_regex_redirected
  52. dev_port = Rails.application.routes.default_url_options[:port]
  53. dev_hosts = ['127.0.0.1', 'localhost', Rails.application.routes.default_url_options[:host]].uniq.join('|')
  54. dev_from = "http://(?:#{dev_hosts}):#{dev_port}"
  55. regex_s = "^(Redirected to )#{dev_from}(.*)"
  56. Regexp.new(regex_s)
  57. end
  58. def ansi_trace(trace, symbol)
  59. match = trace.match(/(↳ )?(.*:\d+)(:in `)?(.*'?)/) # only m2(=file) and m4(=optional function) are useful
  60. return trace unless match
  61. _, m2, _, m4 = match.captures
  62. "#{symbol} #{m2} #{BOLD}#{m4.chop}#{CLEAR}"
  63. end
  64. def two_captures_last_as_bold(message, regex)
  65. match = message.match(regex)
  66. return "unmatched: #{message}" unless match
  67. m1, m2 = match.captures
  68. "#{m1}#{BOLD}#{m2}#{CLEAR}"
  69. end
  70. def alter(log)
  71. if log.name =~ /^(ActionView|ActiveRecord)::Base/
  72. log.level = :debug
  73. log.message.lstrip!
  74. if log.name == 'ActiveRecord::Base'
  75. unbold!(log.message)
  76. if log.message.starts_with?('↳ ')
  77. log.message = ansi_trace(log.message, '⇄')
  78. else
  79. sql_match = log.message.match(/\s+\[\[.*\]\]$/)
  80. if sql_match
  81. sql_command = sql_match.pre_match
  82. sql_type, sql_entry = sql_command.split("\e[0m")
  83. sql_color_entry = sql_entry.match(ANSI_REGEX).to_s
  84. sql_args = JSON.parse(sql_match.to_s).map(&:last)
  85. sql_args.each_with_index do |val, index|
  86. sql_arg = val.inspect
  87. sql_arg = "'#{val.gsub("'", "''")}'" if val.is_a?(String)
  88. sql_entry.gsub!("$#{index + 1}", colorize(sql_arg, BOLD) + sql_color_entry)
  89. end
  90. log.message = [sql_type, sql_entry].join(CLEAR)
  91. end
  92. end
  93. elsif log.name == 'ActionView::Base'
  94. match = log.message.match(/^Rendered( layout| collection of|) (.*?\.erb)(.*)(\(Duration:.*\))/)
  95. if match
  96. m1, m2, m3, m4 = match.captures
  97. duration = m4.match(/Duration: (\d+\.?\d*)ms/).match(1).to_f
  98. duration = duration < RENDERED_VIEW_DURATION ? '' : m4.to_s
  99. log.message = "⇤ Rendered#{m1} app/views/#{m2}#{m3}#{duration}"
  100. end
  101. end
  102. end
  103. log
  104. end
  105. def draw_fatal(char = CHAR_FATAL) = BG_MAGENTA + BOLD + TEXT_WHITE + char + CLEAR
  106. def build_prefix(char) = "#{tags} #{origin}#{colorize(char)}"
  107. def build_terminus = "#{tags} #{origin} #{TERMINUS_STRING} "
  108. def centerize(text, max_length = CENTER_SIZE) = text.reverse.truncate(max_length).reverse.center(max_length)
  109. def origin
  110. true_class = log.name == log.name.upcase_first
  111. taint = true_class ? TEXT_CYAN : TEXT_GRAY_400
  112. colorize(centerize(log.name), taint)
  113. end
  114. def stackisize(items)
  115. return '' if items.empty?
  116. traces = items.map { |item| ansi_trace(item, '➟') }
  117. "\n#{traces.join("\n")}"
  118. end
  119. def build_dimensions(dimensions)
  120. "#{tags} #{origin} #{dimensions.rails} "
  121. end
  122. def compute_useful_length
  123. IO.console.winsize[1] - FOREMAN_PREFIX_LENGTH
  124. rescue StandardError
  125. FAILOVER_WRAP
  126. end
  127. def unbold!(text) = text.gsub!(BOLD, '')
  128. def message
  129. colorize(log.message) if log.message
  130. end
  131. def payload
  132. return unless log.payload
  133. log.payload.ai(indent: 2, object_id: false)
  134. end
  135. def exception
  136. return unless log.exception
  137. if log.exception.is_a?(Semantic::TagWrapError)
  138. exc_wrapper = log.exception
  139. # puts "TAG_WRAP detected #{exc_wrapper.tag}"
  140. exc = exc_wrapper.error
  141. log.tags = Array.wrap(exc_wrapper.tag)
  142. else
  143. exc = log.exception
  144. end
  145. clazz = colorize("#{exc.class}\n", color_map[:fatal])
  146. message = colorize(exc.message.chomp(''), color_map[:error])
  147. backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace)) # TODO: backtrace_cleaner might be optionally disable from Live::Constant
  148. "#{clazz}#{message}#{backtrace}"
  149. end
  150. def level_char
  151. case log.level
  152. when :info, :debug then ' '
  153. else log.level.to_s.chr.upcase
  154. end
  155. end
  156. def wrap_level(length, *items)
  157. prefix = log.dimensions ? build_dimensions(log.dimensions) : build_prefix(level_char)
  158. continuation = build_prefix('┆')
  159. result = items.map do |item|
  160. Semantic::AnsiWrapper.wrap(item, length, prefix, continuation)
  161. end
  162. if log.dimensions&.terminus
  163. terminus = Semantic::AnsiWrapper.wrap(' ', length, build_terminus)
  164. result << terminus
  165. end
  166. log.dimensions&.before&.times { result.unshift('') }
  167. log.dimensions&.after&.times { result << '' }
  168. result.compact.join("\n")
  169. end
  170. end
  171. end