-
-
Save indigoviolet/e14fa531b530b532e9b40d25e7c4933d to your computer and use it in GitHub Desktop.
fin blog embed
This file contains 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
Contract Integer, Func[Any => Any] => Any | |
public def log_query_count(num_trace_lines=1) | |
# Initialize our counter | |
ActiveRecordQueryCounter.instance.reset | |
# Define a callback to be called each time we encounter a query | |
# event. The callback will print out the trace | |
callback = lambda do |_name, _start, _finish, _id, payload| | |
if payload[:name] != 'SCHEMA' | |
Rails.logger.info(tag: 'log_query_count', message: "Query # #{ActiveRecordQueryCounter.instance.query_count}: #{payload[:name]}") | |
ActiveRecordQueryCounter.instance.trace(num_trace_lines).each do |line| | |
Rails.logger.info(tag: 'log_query_count', message: line) | |
end | |
end | |
end | |
Rails.logger.info(tag: 'log_query_count', message: "Starting to count queries, #{ActiveRecordQueryCounter.instance.query_count} so far") | |
# Subscribe the block to query events, and hook up the events to | |
# the callback we defined above | |
result = ActiveSupport::Notifications.subscribed(callback, 'sql.active_record') { yield } | |
Rails.logger.info(tag: 'log_query_count', message: "Total query count: #{ActiveRecordQueryCounter.instance.query_count}") | |
# Remember to return the result from our block | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment