Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Redis' logger option #211

Merged
merged 1 commit into from May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 32 additions & 1 deletion lib/mock_redis.rb
Expand Up @@ -22,6 +22,7 @@ class MockRedis
:path => nil,
:timeout => 5.0,
:password => nil,
:logger => nil,
:db => 0,
:time_class => Time,
}.freeze
Expand Down Expand Up @@ -65,6 +66,10 @@ def db
options[:db]
end

def logger
options[:logger]
end

def time_at(timestamp)
options[:time_class].at(timestamp)
end
Expand All @@ -86,7 +91,9 @@ def respond_to?(method, include_private = false)
end

ruby2_keywords def method_missing(method, *args, &block)
@db.send(method, *args, &block)
logging([[method, *args]]) do
@db.send(method, *args, &block)
end
end

def initialize_copy(source)
Expand Down Expand Up @@ -139,4 +146,28 @@ def _parse_options(options)

options
end

def logging(commands)
return yield unless logger&.debug?

begin
commands.each do |name, *args|
logged_args = args.map do |a|
if a.respond_to?(:inspect) then a.inspect
elsif a.respond_to?(:to_s) then a.to_s
else
# handle poorly-behaved descendants of BasicObject
klass = a.instance_exec { (class << self; self end).superclass }
"\#<#{klass}:#{a.__id__}>"
end
end
logger.debug("[MockRedis] command=#{name.to_s.upcase} args=#{logged_args.join(' ')}")
end

t1 = Time.now
yield
ensure
logger.debug("[MockRedis] call_time=%0.2f ms" % ((Time.now - t1) * 1000)) if t1
end
end
end
9 changes: 9 additions & 0 deletions spec/mock_redis_spec.rb
Expand Up @@ -81,4 +81,13 @@
end
end
end

describe 'supplying a logger' do
it 'logs redis commands' do
logger = double('Logger', debug?: true, debug: nil)
mock_redis = MockRedis.new(logger: logger)
expect(logger).to receive(:debug).with(/command=HMGET args="hash" "key1" "key2"/)
mock_redis.hmget("hash", "key1", "key2")
end
end
end