Skip to content

Instantly share code, notes, and snippets.

@gaffneyc
Created November 16, 2012 16:47
Show Gist options
  • Save gaffneyc/4088877 to your computer and use it in GitHub Desktop.
Save gaffneyc/4088877 to your computer and use it in GitHub Desktop.
Instrumenting ActiveRecord with StatsD
ActiveSupport::Notifications.subscribe("sql.active_record") do |name, start, finish, id, payload|
if payload[:sql] =~ /^\s*(SELECT|DELETE|INSERT|UPDATE) /
method = $1.downcase
table = nil
# Determine the table name for instrumentation. The below regexes work on
# mysql but not sqlite. Probably won't work on postgresql either.
case method
when "select", "delete"
table = $1 if payload[:sql] =~ / FROM `(\w+)`/
when "insert"
table = $1 if payload[:sql] =~ /^\s*INSERT INTO `(\w+)`/
when "update"
table = $1 if payload[:sql] =~ /^\s*UPDATE `(\w+)`/
end
# active_record.select
StatsD.increment("active_record.#{method}")
if table
StatsD.increment("active_record.#{table}.#{method}")
StatsD.timing("active_record.#{table}.#{method}.query_time", (finish - start) * 1000, 1)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment