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.

252 lines
8.6 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
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. CENTER_SIZE = 20
  9. FOREMAN_PREFIX_LENGTH = 18
  10. FAILOVER_WRAP = 80
  11. CHAR_FATAL = '⯶'.freeze
  12. TERMINUS_STRING = '╙─╜'.freeze
  13. RENDERED_VIEW_DURATION = 100
  14. TOTAL_RENDERED_VIEW_DURATION = RENDERED_VIEW_DURATION * 5
  15. def initialize
  16. super(color_map:
  17. ColorMap.new(
  18. debug: CLEAR + TEXT_GRAY_400,
  19. info: CLEAR + TEXT_GRAY_100,
  20. warn: CLEAR + BG_YELLOW + TEXT_BLACK,
  21. error: CLEAR + BG_RED + TEXT_WHITE,
  22. fatal: CLEAR + BG_MAGENTA + BOLD + TEXT_WHITE
  23. ))
  24. @memory = nil
  25. end
  26. def call(log, logger)
  27. # puts 'ok'
  28. log = alter(log)
  29. self.log = log
  30. self.logger = logger
  31. self.color = color_map[log.level]
  32. wrap_level(compute_useful_length, message, payload, exception)
  33. end
  34. def reject(log)
  35. return true if log.name == 'ActionView::Base' && log.message&.starts_with?(' Rendering')
  36. true if log.name == 'Rails' && log.message&.starts_with?('Loaded')
  37. end
  38. private
  39. def tags
  40. first_tag = log.tags.empty? ? 'none' : log.tags.first
  41. first_tag.truncate(CENTER_SIZE).center(CENTER_SIZE)
  42. end
  43. def named_tags
  44. return if log.named_tags.empty?
  45. log.named_tags
  46. end
  47. def build_regex_redirected
  48. dev_port = Rails.application.routes.default_url_options[:port]
  49. dev_hosts = ['127.0.0.1', 'localhost', Rails.application.routes.default_url_options[:host]].uniq.join('|')
  50. dev_from = "http://(?:#{dev_hosts}):#{dev_port}"
  51. regex_s = "^(Redirected to )#{dev_from}(.*)"
  52. Regexp.new(regex_s)
  53. end
  54. def ansi_trace(trace, symbol)
  55. match = trace.match(/(↳ )?(.*:\d+)(:in `)?(.*'?)/) # only m2(=file) and m4(=optional function) are useful
  56. return trace unless match
  57. _, m2, _, m4 = match.captures
  58. "#{symbol} #{m2} #{BOLD}#{m4.chop}#{CLEAR}"
  59. end
  60. def two_captures_last_as_bold(message, regex)
  61. match = message.match(regex)
  62. return "unmatched: #{message}" unless match
  63. m1, m2 = match.captures
  64. "#{m1}#{BOLD}#{m2}#{CLEAR}"
  65. end
  66. def alter(log)
  67. if log.name == 'Rails'
  68. if log.message
  69. log.message.lstrip!
  70. log.message.chomp!('')
  71. if log.message.starts_with?('Started')
  72. rails = '╓─╖'
  73. before = 1
  74. if @memory
  75. rails = "#{@memory}"
  76. before = 0
  77. end
  78. log.dimensions = Semantic::AnsiDimensions.new(rails:, before:)
  79. @memory = nil
  80. log.message = two_captures_last_as_bold(log.message, /(^Started \w* )"(.*?)"/)
  81. elsif log.message.starts_with?('Parameters')
  82. parameters = log.message.match(/Parameters: ({.*}$)/).match(1)
  83. parameters = JSON.parse(parameters.gsub('=>', ':'), symbolize_names: true)
  84. parameters = parameters.ai(ruby19_syntax: true, plain: true, multiline: false)
  85. parameters = parameters.gsub(/\w*:/) { |key| "#{TEXT_GRAY_200}#{key.chop}#{color_map[:debug]}:" }
  86. parameters = parameters.gsub(/: ".*?"/) do |value|
  87. ": \"#{TEXT_YELLOW}#{value[3..-2]}#{color_map[:debug]}\""
  88. end
  89. log.message = "Parameters: #{parameters}"
  90. log.level = :debug
  91. elsif log.message.starts_with?('Completed')
  92. m1, m2, m3, m4 = log.message.match(/^Completed (\d+) (.*) in (\d+\.?\d*)ms (.*)$/).captures
  93. http_code = m1.to_i
  94. duration = m3.to_f
  95. duration = duration > TOTAL_RENDERED_VIEW_DURATION ? " in #{m3}ms #{m4}" : ''
  96. log.message = "Completed #{BOLD}#{http_code}#{CLEAR} #{m2}#{duration}"
  97. if http_code / 100 == 2
  98. log.dimensions = Semantic::AnsiDimensions.new(rails: TERMINUS_STRING, after: 1)
  99. elsif http_code / 100 == 3
  100. @memory = '║'
  101. log.dimensions = Semantic::AnsiDimensions.new(rails: "#{@memory}")
  102. elsif http_code / 100 == 4
  103. log.dimensions = Semantic::AnsiDimensions.new(rails: '╙╨╜')
  104. elsif http_code / 100 == 5
  105. log.dimensions = Semantic::AnsiDimensions.new(rails: "#{draw_fatal}")
  106. end
  107. elsif log.message =~ /^(Processing|Parameters)/
  108. log.level = :debug
  109. if log.message =~ /^Processing/
  110. log.message = two_captures_last_as_bold(log.message, /(^Processing by \w*#\w* as )(.*)/)
  111. end
  112. elsif log.message =~ /Redirected/
  113. log.level = :debug
  114. @regex_redirected ||= build_regex_redirected # lazy building
  115. log.message = two_captures_last_as_bold(log.message, @regex_redirected)
  116. end
  117. elsif log.exception
  118. log.dimensions = Semantic::AnsiDimensions.new(
  119. rails: "#{draw_fatal(log.level.to_s.chr.upcase)}",
  120. after: 1,
  121. terminus: true
  122. )
  123. end
  124. elsif log.name =~ /^(ActionView|ActiveRecord)::Base/
  125. log.level = :debug
  126. log.message.lstrip!
  127. if log.name == 'ActiveRecord::Base'
  128. unbold!(log.message)
  129. if log.message.starts_with?('↳ ')
  130. log.message = ansi_trace(log.message, '⇄')
  131. else
  132. sql_match = log.message.match(/\s+\[\[.*\]\]$/)
  133. if sql_match
  134. sql_command = sql_match.pre_match
  135. sql_type, sql_entry = sql_command.split("\e[0m")
  136. sql_color_entry = sql_entry.match(ANSI_REGEX).to_s
  137. sql_args = JSON.parse(sql_match.to_s).map(&:last)
  138. sql_args.each_with_index do |val, index|
  139. sql_arg = val.inspect
  140. sql_arg = "'#{val.gsub("'", "''")}'" if val.is_a?(String)
  141. sql_entry.gsub!("$#{index + 1}", colorize(sql_arg, BOLD) + sql_color_entry)
  142. end
  143. log.message = [sql_type, sql_entry].join(CLEAR)
  144. end
  145. end
  146. elsif log.name == 'ActionView::Base'
  147. match = log.message.match(/^Rendered( layout| collection of|) (.*?\.erb)(.*)(\(Duration:.*\))/)
  148. if match
  149. m1, m2, m3, m4 = match.captures
  150. duration = m4.match(/Duration: (\d+\.?\d*)ms/).match(1).to_f
  151. duration = duration < RENDERED_VIEW_DURATION ? '' : m4.to_s
  152. log.message = "⇤ Rendered#{m1} app/views/#{m2}#{m3}#{duration}"
  153. end
  154. end
  155. end
  156. log
  157. end
  158. def draw_fatal(char = CHAR_FATAL) = BG_MAGENTA + BOLD + TEXT_WHITE + char + CLEAR
  159. def origin = colorize(centerize(log.name), TEXT_CYAN)
  160. def build_prefix(char) = "#{tags} #{origin}#{colorize(char)}"
  161. def build_terminus = "#{tags} #{origin} #{TERMINUS_STRING} "
  162. def colorize(text, tint = color) = "#{tint}#{text}#{CLEAR}"
  163. def centerize(text) = text.reverse.truncate(CENTER_SIZE).reverse.center(CENTER_SIZE)
  164. def stackisize(items)
  165. return '' if items.empty?
  166. traces = items.map { |item| ansi_trace(item, '➟') }
  167. "\n#{traces.join("\n")}"
  168. end
  169. def build_dimensions(dimensions)
  170. "#{tags} #{origin} #{dimensions.rails} "
  171. end
  172. def compute_useful_length
  173. IO.console.winsize[1] - FOREMAN_PREFIX_LENGTH
  174. rescue StandardError
  175. FAILOVER_WRAP
  176. end
  177. def unbold!(text) = text.gsub!(BOLD, '')
  178. def message
  179. colorize(log.message) if log.message
  180. end
  181. def payload
  182. return unless log.payload
  183. log.payload.ai(indent: 2, object_id: false)
  184. end
  185. def exception
  186. return unless log.exception
  187. exc = log.exception
  188. clazz = colorize("#{exc.class}\n", color_map[:fatal])
  189. message = colorize(exc.message.chomp(''), color_map[:error])
  190. backtrace = stackisize(Rails.backtrace_cleaner.clean(exc.backtrace))
  191. "#{clazz}#{message}#{backtrace}"
  192. end
  193. def level_char
  194. case log.level
  195. when :info, :debug then ' '
  196. else log.level.to_s.chr.upcase
  197. end
  198. end
  199. def wrap_level(length, *items)
  200. prefix = log.dimensions ? build_dimensions(log.dimensions) : build_prefix(level_char)
  201. continuation = build_prefix('┆')
  202. result = items.map do |item|
  203. Semantic::AnsiWrapper.wrap(item, length, prefix, continuation)
  204. end
  205. if log.dimensions&.terminus
  206. terminus = Semantic::AnsiWrapper.wrap(' ', length, build_terminus)
  207. result << terminus
  208. end
  209. log.dimensions&.before&.times { result.unshift('') }
  210. log.dimensions&.after&.times { result << '' }
  211. result.compact.join("\n")
  212. end
  213. end
  214. end