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.

74 lines
2.5 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
  1. module Semantic
  2. module Subscribers
  3. # LogSubscriber for event_group :active_record
  4. class ActiveRecord < LogSubscriber
  5. include AnsiColors
  6. IGNORE_PAYLOAD_NAMES = %w[SCHEMA EXPLAIN].freeze
  7. TRANSACTION_TAINT = AnsiColors::DARK_TEXT_CYAN
  8. def sql(event)
  9. name = event.payload[:name]
  10. return if IGNORE_PAYLOAD_NAMES.include?(name)
  11. category, model, *remaining = name.split.reverse
  12. return if category == 'TRANSACTION'
  13. case category
  14. when 'Count'
  15. statement_taint = AnsiColors::TEXT_GRAY_300
  16. name = "#{category} #{model}"
  17. when 'Load'
  18. name = if event.payload[:cached]
  19. statement_taint = AnsiColors::TEXT_GRAY_300
  20. name = "Cache #{model}"
  21. else
  22. statement_taint = TEXT_BLUE
  23. row_count = event.payload[:row_count]
  24. name = "#{category} #{row_count} #{model.pluralize(row_count)}"
  25. end
  26. when 'Update', 'Create', 'Destroy'
  27. name = "#{category} #{model}"
  28. category_taint = TRANSACTION_TAINT
  29. statement_taint = TEXT__PINK
  30. increment_transaction_local(event.payload[:transaction].uuid, category.downcase.to_sym)
  31. else raise "unknown sql category: <#{category}>"
  32. end
  33. name = "#{name} #{remaining.join(' ')}" if remaining.any?
  34. name = colorize(name, category_taint) if category_taint
  35. statement = colorize(event.payload[:sql], statement_taint)
  36. logger.debug("#{name} #{statement}")
  37. end
  38. def start_transaction(event)
  39. logger.info(colorize('Begin', TRANSACTION_TAINT))
  40. end
  41. def transaction(event)
  42. outcome = colorize(event.payload[:outcome].capitalize, TRANSACTION_TAINT)
  43. summary = transaction_summary(event.payload[:transaction])
  44. logger.info("#{outcome} (#{summary})")
  45. end
  46. def instantiation(event); end
  47. def strict_loading_violation(event) = any_hook event
  48. private
  49. def transaction_summary(transaction)
  50. transaction_local(transaction.uuid)
  51. .select { |_, value| value.positive? }
  52. .map { |k, v| "#{v} #{k.to_s.pluralize(v)}" }
  53. .join(',')
  54. end
  55. def increment_transaction_local(transaction_id, sql_command) = transaction_local(transaction_id)[sql_command] += 1
  56. def thread_local = Thread.current[self.class.to_s] ||= {}
  57. def transaction_local(transaction_id)
  58. thread_local[transaction_id] ||= { update: 0, create: 0, destroy: 0 }
  59. end
  60. end
  61. end
  62. end