Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created August 25, 2012 01:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattetti/3458669 to your computer and use it in GitHub Desktop.
Save mattetti/3458669 to your computer and use it in GitHub Desktop.
Instrument ActiveRecord and push the results to Statsd
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
@mattetti
Copy link
Author

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.

@mattetti
Copy link
Author

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