Created
July 1, 2011 15:42
-
-
Save jacortinas/1058808 to your computer and use it in GitHub Desktop.
Redis Logging
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
# config/initializers/app_config.rb | |
# An initializer that contains config stuff | |
# ... | |
class RedisConfig < Settingslogic | |
source "#{Rails.root}/config/redis.yml" | |
namespace Rails.env | |
end | |
# ... |
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
# config/initializers/redis.rb | |
require 'redis' | |
# Monkey Patching for profit. The old way of doing this | |
# using method_missing added a little bit too much overhead. | |
# It also showed the commands out of order. This is more accurate. | |
class Redis | |
class Client | |
alias :old_initialize :initialize | |
alias :old_logging :logging | |
def initialize(options = {}) | |
old_initialize(options) | |
@notification = options[:notification] | |
end | |
def logging(commands, &block) | |
return old_logging(commands, &block) unless @notification | |
ActiveSupport::Notifications.instrument('request.redis', commands: commands) do | |
return old_logging(commands, &block) | |
end | |
end | |
end | |
end | |
class RedisInstrumenter < ActiveSupport::LogSubscriber | |
def request(event) | |
return unless logger.debug? | |
name = "%s (%.2fms)" % ["Redis", event.duration] | |
cmds = event.payload[:commands] | |
output = " #{color(name, RED, true)}" | |
cmds.each do |name, *args| | |
if args.present? | |
output << " [ #{name.to_s.upcase} #{args.join(" ")} ]" | |
else | |
output << " [ #{name.to_s.upcase} ]" | |
end | |
end | |
debug output | |
end | |
end | |
if Rails.env.development? || Rails.env.test? | |
RedisInstrumenter.attach_to(:redis) | |
end | |
REDIS = Redis.new(RedisConfig) |
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
# config/redis.yml | |
defaults: &defaults | |
host: 127.0.0.1 | |
notification: true | |
development: | |
<<: *defaults | |
db: 0 | |
test: | |
<<: *defaults | |
db: 1 | |
production: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment