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.

241 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
10 months ago
11 months ago
11 months ago
10 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
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
10 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. ansi_wrap(message, CONTENT_COLOR_MAP[log.level])
  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_wrap(log.name.truncate(NAME_MAX_SIZE).center(NAME_MAX_SIZE), ANSI_DEBUG)
  80. end
  81. def exception
  82. return unless log.exception
  83. backtrace = backtrace(log.exception)
  84. "#{ansi_wrap(log.exception.class,
  85. ANSI_REVERSED_WARNING)} #{ansi_wrap(log.exception.message, ANSI_REVERSED_ERROR)}#{backtrace}"
  86. end
  87. def call(log, logger)
  88. self.log = transform_log(log)
  89. self.color = color_map[self.log.level]
  90. self.logger = logger
  91. before_message + [message, payload, exception].compact.join(' ')
  92. end
  93. private
  94. def ansi_wrap(text, ansi_code)
  95. "#{ansi_code}#{text}#{color_map.clear}"
  96. end
  97. def draw_rails(char)
  98. ansi_wrap("#{char}", color)
  99. end
  100. def continuation
  101. draw_rails('┆')
  102. end
  103. # transform log before display
  104. def transform_log(log)
  105. case log.name
  106. when 'ActionView::Base' then transform_action_view_base(log)
  107. when 'Rails' then transform_rails_log(log)
  108. when 'ActiveRecord::Base'
  109. log.message = transform_active_record_message(log.message)
  110. log
  111. else log end
  112. end
  113. def transform_rails_log(log)
  114. return log unless log.message
  115. log.message = transform_rails_message(log.message.rstrip)
  116. log.level = :debug if log.message =~ /^#{PREFIX_RAILS_INTERNAL}(Processing|Parameters)/
  117. log
  118. end
  119. def transform_active_record_message(message)
  120. message = message.lstrip.sub(/^↳ /, 'Processed by ')
  121. "#{PREFIX_RECORD_INTERNAL}#{message.lstrip}"
  122. end
  123. def transform_rails_message(message)
  124. case message
  125. when /^Completed/ then transform_rails_completed(message)
  126. when /^Started/ then two_captures_last_as_bold(message, /(^Started \w* )"(.*?)"/)
  127. when /^ Parameters/ then transform_rails_parameters(message)
  128. when /^Processing/ then transform_rails_processing(message)
  129. else message end
  130. end
  131. def transform_rails_processing(message)
  132. message = two_captures_last_as_bold(message, /(^Processing by \w*#\w* as )(.*)/)
  133. "#{PREFIX_RAILS_INTERNAL}#{message}"
  134. end
  135. def transform_rails_parameters(message)
  136. parameters = message.lstrip.match(/Parameters: ({.*}$)/).match(1)
  137. parameters = JSON.parse(parameters.gsub('=>', ':'), symbolize_names: true)
  138. "#{PREFIX_RAILS_INTERNAL}Parameters: #{parameters.ai(ruby19_syntax: true, plain: true, multiline: false)}"
  139. end
  140. def transform_rails_completed(message)
  141. m1, m2, m3, m4 = message.match(/^Completed (\d*) (.*) in (\d*)ms(.*)$/).captures
  142. http_code = ansi_wrap("#{m1} #{m2}", ANSI_BOLD)
  143. message = "Completed #{http_code} in #{m3}ms"
  144. message += m4 if m3.to_i > COMPLETED_DURATION
  145. message += "\n" if m1 =~ /^[23]/
  146. message
  147. end
  148. def two_captures_last_as_bold(message, regex)
  149. m1, m2 = message.match(regex).captures
  150. "#{m1}#{ansi_wrap(m2, ANSI_BOLD)}"
  151. end
  152. def transform_action_view_base(log)
  153. log.level, message = transform_log_debug_lstrip(log)
  154. message = transform_rendered_message_with_filename(message)
  155. message = transform_duration_strip(message)
  156. log.message = "#{PREFIX_ACTION_INTERNAL}#{message}"
  157. log
  158. end
  159. def transform_duration_strip(message)
  160. md2 = message.match(/( \(Duration: \d+\.?\d?ms.*\))/)
  161. md3 = md2.match(1).match(/Duration: (\d+\.?\d?)ms/)
  162. duration = md3.match(1).to_f
  163. duration < RENDERED_VIEW_DURATION ? md2.pre_match : message
  164. end
  165. def transform_rendered_message_with_filename(message)
  166. md = message.match(/^Rendered( layout| collection of|) (.*?\.erb)/)
  167. filename = "app/views/#{md.match(2)}"
  168. log.message = "Rendered#{md.match(1)} #{filename}#{md.post_match}"
  169. end
  170. def transform_log_debug_lstrip(log)
  171. [:debug, log.message.lstrip]
  172. end
  173. def wrap_message(message)
  174. message, space_prefix = split_spaces_in_front(message)
  175. message = Wrapper.wrap("#{CONTENT_COLOR_MAP[log.level]}#{message}",
  176. before_message(wrapped: true) + space_prefix.to_s,
  177. compute_useful_length - space_prefix.length)
  178. "#{space_prefix}#{message}"
  179. end
  180. def split_spaces_in_front(message)
  181. md = message.match(/^\s*/)
  182. [md.post_match, md.match(0)]
  183. end
  184. def compute_useful_length
  185. IO.console.winsize[1] - TERMINAL_PREFIX - before_message.length + CONTENT_PREFIX.length + 12
  186. rescue StandardError
  187. 100 # FIXME: CONSTANTIZE, only useful in DEBUGGER, no IO.console detected!
  188. end
  189. def before_message(wrapped: false)
  190. [name, wrapped ? continuation : level, tags, named_tags, duration].compact.join(' ') + CONTENT_PREFIX
  191. end
  192. def backtrace(exception)
  193. root_path = Rails.root.to_s
  194. stack = exception.backtrace.select { |line| line.starts_with?(root_path) }
  195. stack = stack.map { |line| line.delete_prefix("#{root_path}/") }
  196. return "\n" unless stack.count.positive?
  197. stack_message = PREFIX_BUG_INTERNAL
  198. stack_message += stack.join("\n#{before_message}#{ANSI_ERROR}#{PREFIX_BUG_INTERNAL}")
  199. "\n#{before_message}#{ansi_wrap(stack_message, ANSI_ERROR)}\n"
  200. end
  201. end