Created
August 25, 2012 01:47
-
-
Save mattetti/3458669 to your computer and use it in GitHub Desktop.
Instrument ActiveRecord and push the results to Statsd
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
SQL_PARSER_REGEXP = /^(\w+)\s(\w+)\s\W*(\w+)/ | |
ActiveSupport::Notifications.subscribe "sql.active_record" do |name, start, finish, id, payload| | |
if payload[:name] == "SQL" | |
if Thread.current[:stats_context] # where I store the name of the request context | |
payload[:sql] =~ SQL_PARSER_REGEXP # $1 will be the query type, $3 the table | |
Statsd.timing("#{Thread.current[:stats_context]}.sql.#{$3}.#{$1}.query_time", | |
(finish - start) * 1000, 1) | |
end | |
end | |
end |
To be a bit more precise, in the AR version I'm using, the code above will only get you inserts and deletes. payload[:name]
will be "ModelName Load" for some selects and updates and counts don't seem to set a payload name. You therefore need to write some basic parser code to capture inserts, selects, updates and deletes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, by filtering on the payload "SQL" and using the provided regexp, you will only get part of the queries. I'll let you dig to find how to get the rest.