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.

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