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.

228 lines
7.4 KiB

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