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.

245 lines
8.0 KiB

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