Robot Has No Heart

Xavier Shay blogs here

A robot that does not have a heart

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

  1. John says:

    I am receiving a 404. Is there a problem with the link?

  2. Xavier Shay says:

    Ah yes sorry. I'll move it to github in the next few days.

  3. Xavier Shay says:

    All fixed now

  4. John says:

    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

  5. Xavier Shay says:

    Fork is easiest, that'd be ace, then I can just pull your patch.

  6. John says:

    Hey Xavier -

    Forked in my changes, for what I found useful.
    git://github.com/retr0h/sql-counter.git

    John

Post a comment


(lesstile enabled - surround code blocks with ---)

A pretty flower Another pretty flower