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.

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