Home > other >  Rails - how to count the total number of SQL queries generated on each page?
Rails - how to count the total number of SQL queries generated on each page?

Time:08-11

I have an old Rails(4.2) legacy app with lots of pages(controller actions) and I would like to profile it and find the slowest ones(with the largest number of SQL queries).

How can this be achieved?

Basically, I'm trying to find the low-hanging fruits and the biggest pain points.

CodePudding user response:

The rack-mini-profiler is what you need!

https://github.com/MiniProfiler/rack-mini-profiler

CodePudding user response:

So far I've come up with the following method which is a bit inconvenient but seems to get the job done as long as you're fine with profiling one page/action per minute.

class RedisSQLQueryCounter
  def call(_, _, _, _, values)
    cache_key = Time.now.strftime '%H%M'
    result = $redis.incr cache_key

    Rails.logger.debug "SQL counter: #{result}"
  end
end

sql_counter_subscriber = RedisSQLQueryCounter.new
ActiveSupport::Notifications.subscribe("sql.active_record", sql_counter_subscriber)
watch -f log/development.log | grep 'SQL counter'
  • Related