Created
August 26, 2012 01:36
-
-
Save mattetti/3473008 to your computer and use it in GitHub Desktop.
Redis instrumentation
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
::Redis::Client.class_eval do | |
# Support older versions of Redis::Client that used the method | |
# +raw_call_command+. | |
call_method = ::Redis::Client.new.respond_to?(:call) ? :call : :raw_call_command | |
def call_with_stats_trace(*args, &blk) | |
method_name = args[0].is_a?(Array) ? args[0][0] : args[0] | |
start = Time.now | |
begin | |
call_without_stats_trace(*args, &blk) | |
ensure | |
METRICS.timing("#{Thread.current[:stats_context] || 'wild'}.redis.#{method_name.to_s.upcase}.query_time", | |
((Time.now - start) * 1000).round, 1) rescue nil | |
end | |
end | |
alias_method :call_without_stats_trace, call_method | |
alias_method call_method, :call_with_stats_trace | |
end if defined?(::Redis::Client) |
Apply the same approach to instrument call_pipelined
.
Thread.current[:stats_context]
is used to set a context such as the name of an API endpoint or "http.#{controller_name}.#{action}" so my Redis instrumentation reports are scoped and I can compare the response time of a request with the time spent in AR, Redis and in external HTTP requests. In Graphite, you can look for data using wild cards and therefore find all the instrumentation Redis stats.
This is the way that I prefer to monkey patch things. I find it very rare where Module#alias_method is actually required.
module StatsCollector
call_method = ::Redis::Client.method_defined?(:call) ? :call : :raw_call_method
define_method(call_method) do |*args, *blk|
method_name = args[0].is_a?(Array) ? args[0][0] : args[0]
start = Time.now
begin
super(*args, &blk)
ensure
METRICS.timing("#{Thread.current[:stats_context] || 'wild'}.redis.#{method_name.to_s.upcase}.query_time",
((Time.now - start) * 1000).round, 1) rescue nil
end
end
end
redis = Redis.new(:host => '127.0.0.1', :port => 6379, :password => 'xyz')
redis.extend(StatsCollector)
redis.set('foo', '1')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is in reference to http://www.mikeperham.com/2012/08/25/using-statsd-with-rails/ and based on https://github.com/evanphx/newrelic-redis