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.

236 lines
7.2 KiB

11 months ago
10 months ago
11 months ago
10 months ago
11 months ago
11 months ago
10 months ago
10 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
11 months ago
11 months ago
11 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
11 months ago
10 months ago
11 months ago
  1. require_relative 'wrapper'
  2. require_relative 'base'
  3. require 'io/console'
  4. require 'amazing_print'
  5. require 'json'
  6. # Opinioned Rails custom formatter
  7. class BasicFormatter < SemanticLogger::Formatters::Color # rubocop:disable Metrics/ClassLength
  8. NAME_MAX_SIZE = 25
  9. TERMINAL_PREFIX = ENV['TERMINAL_PREFIX'].to_i || 0
  10. CONTENT_PREFIX = ' '.freeze
  11. PREFIX_RAILS_INTERNAL = '⬂ '.freeze
  12. PREFIX_RECORD_INTERNAL = '⬄ '.freeze
  13. PREFIX_ACTION_INTERNAL = '⬃ '.freeze
  14. PREFIX_BUG_INTERNAL = '➟ '.freeze
  15. RENDERED_VIEW_DURATION = 100
  16. COMPLETED_DURATION = RENDERED_VIEW_DURATION * 5
  17. ANSI_RESET = "\e[0m".freeze
  18. ANSI_BOLD = "\e[1m".freeze
  19. ANSI_DEBUG = "\e[90m".freeze
  20. ANSI_INFO = SemanticLogger::AnsiColors::GREEN
  21. ANSI_WARN = SemanticLogger::AnsiColors::YELLOW
  22. ANSI_ERROR = "\e[91m".freeze
  23. ANSI_NEUTRAL_INFO = SemanticLogger::AnsiColors::WHITE
  24. ANSI_REVERSED_WARNING = "\e[0;30;43m".freeze
  25. ANSI_REVERSED_ERROR = "\e[1;30;41m".freeze
  26. ANSI_REVERSED_FATAL = "\e[1;30;41m".freeze
  27. CONTENT_COLOR_MAP = ColorMap.new(
  28. debug: ANSI_DEBUG,
  29. info: ANSI_NEUTRAL_INFO,
  30. warn: ANSI_REVERSED_WARNING,
  31. error: ANSI_REVERSED_ERROR,
  32. fatal: ANSI_REVERSED_FATAL
  33. )
  34. # exclude log eagerly!
  35. EXCLUDE_LAMBDA = lambda { |log|
  36. if log.name == 'ActionView::Base'
  37. !log.message.starts_with?(' Rendering')
  38. elsif log.name == 'Rails' && !log.message.nil?
  39. log.message.exclude?('Started GET "/rails/live/reload')
  40. elsif log.name == 'ActiveRecord::Base'
  41. log.message.exclude?('↳ lib/formatters/basic_formatter.rb')
  42. else
  43. true
  44. end
  45. }
  46. def initialize
  47. super(color_map: ColorMap.new(
  48. debug: ANSI_DEBUG,
  49. info: ANSI_INFO,
  50. warn: ANSI_WARN,
  51. error: ANSI_ERROR,
  52. fatal: ANSI_ERROR
  53. ))
  54. end
  55. def message
  56. return unless log.message
  57. message = wrap_message(log.message)
  58. "#{CONTENT_COLOR_MAP[log.level]}#{message}#{color_map.clear}"
  59. end
  60. def payload
  61. return unless log.payload
  62. lines = log.payload.ai(ruby19_syntax: true, indent: 2).split("\n")
  63. first_line = lines.shift
  64. space_prefix = first_line.match(/^\s*/)
  65. lines = lines.map do |l|
  66. "#{before_message(wrapped: true)}#{space_prefix}#{l}"
  67. end
  68. result = lines.unshift(first_line).join("\n")
  69. result.sub!(/\s*/) { |m| '-' * m.length }
  70. result
  71. end
  72. def level
  73. case log.level
  74. when :info, :debug then draw_rails ' '
  75. else draw_rails(log.level.to_s.chr.upcase)
  76. end
  77. end
  78. def name
  79. "#{ANSI_DEBUG}#{log.name.truncate(NAME_MAX_SIZE).center(NAME_MAX_SIZE)}#{color_map.clear}"
  80. end
  81. def exception # rubocop:disable Metrics/AbcSize
  82. return unless log.exception
  83. root_path = Rails.root.to_s
  84. stack = log.exception.backtrace.select { |line| line.starts_with?(root_path) }
  85. stack = stack.map { |line| line.delete_prefix("#{root_path}/") }
  86. "#{ANSI_REVERSED_WARNING}#{log.exception.class}#{color_map.clear} #{ANSI_REVERSED_ERROR}#{log.exception.message}#{color_map.clear}#{backtrace(stack)}" # rubocop:disable Layout/LineLength
  87. end
  88. def call(log, logger)
  89. self.log = transform_log(log)
  90. self.color = color_map[self.log.level]
  91. self.logger = logger
  92. before_message + [message, payload, exception].compact.join(' ')
  93. end
  94. private
  95. def draw_rails(char)
  96. "#{color}#{char}#{color_map.clear}"
  97. end
  98. def continuation
  99. draw_rails('┆')
  100. end
  101. # transform log before display
  102. def transform_log(log)
  103. case log.name
  104. when 'ActionView::Base' then transform_action_view_base(log)
  105. when 'Rails' then transform_rails_log(log)
  106. when 'ActiveRecord::Base'
  107. log.message = transform_active_record_message(log.message)
  108. log
  109. else log end
  110. end
  111. def transform_rails_log(log)
  112. return log unless log.message
  113. log.message = transform_rails_message(log.message.rstrip)
  114. log.level = :debug if log.message =~ /^#{PREFIX_RAILS_INTERNAL}(Processing|Parameters)/
  115. log
  116. end
  117. def transform_active_record_message(message)
  118. message = message.lstrip.sub(/^↳ /, 'Processed by ')
  119. "#{PREFIX_RECORD_INTERNAL}#{message.lstrip}"
  120. end
  121. def transform_rails_message(message)
  122. case message
  123. when /^Completed/ then transform_rails_completed(message)
  124. when /^Started/ then two_captures_last_as_bold(message, /(^Started \w* )"(.*?)"/)
  125. when / Parameters/ then transform_rails_parameters(message)
  126. when /^Processing/ then transform_rails_processing(message)
  127. else message end
  128. end
  129. def transform_rails_processing(message)
  130. message = two_captures_last_as_bold(message, /(^Processing by \w*#\w* as )(.*)/)
  131. "#{PREFIX_RAILS_INTERNAL}#{message}"
  132. end
  133. def transform_rails_parameters(message)
  134. parameters = message.lstrip.match(/Parameters: ({.*}$)/).match(1)
  135. parameters = JSON.parse(parameters.gsub('=>', ':'), symbolize_names: true)
  136. "#{PREFIX_RAILS_INTERNAL}Parameters: #{parameters.ai(ruby19_syntax: true, plain: true, multiline: false)}"
  137. end
  138. def transform_rails_completed(message)
  139. m1, m2, m3, m4 = message.match(/^Completed (\d*) (.*) in (\d*)ms(.*)$/).captures
  140. message = "Completed #{ANSI_BOLD}#{m1} #{m2}#{ANSI_RESET} in #{m3}ms"
  141. message += m4 if m3.to_i > COMPLETED_DURATION
  142. message += "\n" if m1 =~ /^[23]/
  143. message
  144. end
  145. def two_captures_last_as_bold(message, regex)
  146. m1, m2 = message.match(regex).captures
  147. "#{m1}#{ANSI_BOLD}#{m2}#{ANSI_RESET}"
  148. end
  149. def transform_action_view_base(log)
  150. log.level, message = transform_log_debug_lstrip(log)
  151. message = transform_rendered_message_with_filename(message)
  152. message = transform_duration_strip(message)
  153. log.message = "#{PREFIX_ACTION_INTERNAL}#{message}"
  154. log
  155. end
  156. def transform_duration_strip(message)
  157. md2 = message.match(/( \(Duration: \d+\.?\d?ms.*\))/)
  158. md3 = md2.match(1).match(/Duration: (\d+\.?\d?)ms/)
  159. duration = md3.match(1).to_f
  160. duration < RENDERED_VIEW_DURATION ? md2.pre_match : message
  161. end
  162. def transform_rendered_message_with_filename(message)
  163. md = message.match(/^Rendered( layout| collection of|) (.*?\.erb)/)
  164. filename = "app/views/#{md.match(2)}"
  165. log.message = "Rendered#{md.match(1)} #{filename}#{md.post_match}"
  166. end
  167. def transform_log_debug_lstrip(log)
  168. [:debug, log.message.lstrip]
  169. end
  170. def wrap_message(message)
  171. message, space_prefix = split_spaces_in_front(message)
  172. message = Wrapper.wrap("#{CONTENT_COLOR_MAP[log.level]}#{message}",
  173. before_message(wrapped: true) + space_prefix.to_s,
  174. compute_useful_length - space_prefix.length)
  175. "#{space_prefix}#{message}"
  176. end
  177. def split_spaces_in_front(message)
  178. md = message.match(/^\s*/)
  179. [md.post_match, md.match(0)]
  180. end
  181. def compute_useful_length
  182. IO.console.winsize[1] - TERMINAL_PREFIX - before_message.length + CONTENT_PREFIX.length + 12
  183. rescue StandardError
  184. 100 # FIXME: CONSTANTIZE, only useful in DEBUGGER, no IO.console detected!
  185. end
  186. def before_message(wrapped: false)
  187. [name, wrapped ? continuation : level, tags, named_tags, duration].compact.join(' ') + CONTENT_PREFIX
  188. end
  189. def backtrace(stack)
  190. return "\n" unless stack.count.positive?
  191. "\n#{before_message}#{ANSI_ERROR}#{PREFIX_BUG_INTERNAL}#{stack.join("\n#{before_message}#{ANSI_ERROR}#{PREFIX_BUG_INTERNAL}")}#{color_map.clear}\n"
  192. end
  193. def color_content
  194. color
  195. end
  196. end