Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created August 26, 2012 01:36
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattetti/3473008 to your computer and use it in GitHub Desktop.
Save mattetti/3473008 to your computer and use it in GitHub Desktop.
Redis instrumentation
::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)
@mattetti
Copy link
Author

@mattetti
Copy link
Author

Apply the same approach to instrument call_pipelined.

@mattetti
Copy link
Author

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.

@ryanlecompte
Copy link

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