Created
June 12, 2025 14:58
-
-
Save glaucocustodio/67992928f15a626a97cecbcd59fc6292 to your computer and use it in GitHub Desktop.
A module to track/output Active Record queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module QueryTrackable | |
extend ActiveSupport::Concern | |
# | |
# Prints the number of queries and the time spent in milliseconds | |
# Useful to track the performance of isolated classes | |
# | |
# Usage: | |
# | |
# class MyClass | |
# include QueryTrackable | |
# | |
# def my_method | |
# track_active_record_queries do | |
# # your code with queries here | |
# end | |
# end | |
# end | |
# | |
# Example output: `[MyClass] ActiveRecord: 7707.7ms (85 queries, 0 cached)` | |
# | |
included do | |
# inspired by https://github.com/rails/rails/blob/fd49d6a3180244969fb5ab9768d0bc7d9e4df9fe/activerecord/lib/active_record/runtime_registry.rb#L70 | |
def track_active_record_queries | |
cached_queries = 0 | |
queries = 0 | |
runtime_before = Time.current | |
subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |*args| | |
payload = args.last | |
next if ["SCHEMA", "TRANSACTION"].include?(payload[:name]) | |
if payload[:cached] | |
cached_queries += 1 | |
else | |
queries += 1 | |
end | |
end | |
yield | |
runtime_after = Time.current | |
ActiveSupport::Notifications.unsubscribe(subscriber) | |
spent = ((runtime_after - runtime_before) * 1000.0).round(1) | |
log_query_stats(spent, queries, cached_queries) | |
end | |
private | |
def log_query_stats(spent, queries, cached_queries) | |
Rails.logger.debug do | |
"[#{self.class.name}] ActiveRecord: #{spent}ms (#{queries} queries, #{cached_queries} cached)" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative: https://github.com/rubysamurai/query_count