Skip to content

Instantly share code, notes, and snippets.

@indigoviolet
Last active December 26, 2017 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indigoviolet/e14fa531b530b532e9b40d25e7c4933d to your computer and use it in GitHub Desktop.
Save indigoviolet/e14fa531b530b532e9b40d25e7c4933d to your computer and use it in GitHub Desktop.
fin blog embed
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