Logging SQL statistics in rails
When your sysadmin comes to you whinging with a valid concern that your app is reading 60 gazillion records from the DB, you kinda wish you had a bit more information than % time spent in the DB. So I wrote a plugin that counts both the number of selects/updates/inserts/deletes and also the number of records affected.
1 |
git clone git://github.com/xaviershay/sql-counter.git vendor/plugins/sql_counter |
That does the counting, you need to decide how to log it. I am personally quite partial to adding it to the request log line, thus getting stats per request:
1 2 3 4 5 |
# vendor/rails/actionpack/lib/action_controller/benchmarking.rb:75 log_message << " | Select Records: #{ActiveRecord::Base.connection.select_record_count}" log_message << " | Selects: #{ActiveRecord::Base.connection.select_count}" ActiveRecord::Base.connection.reset_counters! |
Don’t forget the last line, otherwise you get cumulative numbers. That may be handy, but I doubt it. We’re only logging selects because that’s all we care about at the moment. I am sure this will change in time.
UPDATE: Moved to github, bzr repo is no longer available
May 16, 2008 at 5:11 PM
I am receiving a 404. Is there a problem with the link?
May 16, 2008 at 5:32 PM
Ah yes sorry. I'll move it to github in the next few days.
May 17, 2008 at 1:27 PM
All fixed now
May 20, 2008 at 5:57 AM
Thanks -
Would you be interested in taking a patch that monkeypatches ActionController::Benchmarking to include the logger lines, or prefer
I just make a fork?
This will prevent ppl from having to manually update the vendor/rails
source.
John
May 20, 2008 at 7:06 AM
Fork is easiest, that'd be ace, then I can just pull your patch.
May 20, 2008 at 7:53 AM
Hey Xavier -
Forked in my changes, for what I found useful.
git://github.com/retr0h/sql-counter.git
John