Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created August 26, 2012 01:36
Show Gist options
  • 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)
@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