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.

247 lines
8.4 KiB

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