Created
November 16, 2012 16:47
-
-
Save gaffneyc/4088877 to your computer and use it in GitHub Desktop.
Instrumenting ActiveRecord with StatsD
This file contains hidden or 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
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