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.

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