Skip to content

Commit dfde2fc

Browse files
committed
Guard all log statements with log_enabled().
Checking log.isEnabledFor() once avoids the often expensive repr_command() calls as well as calls to log.debug() itself. This is a especially large savings in _execute_{pipeline,transaction}().
1 parent c098f32 commit dfde2fc

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

redis/client.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def connect(self, redis_instance):
5858
"Connects to the Redis server if not already connected"
5959
if self._sock:
6060
return
61-
log.debug("connecting to %s:%d/%d", self.host, self.port, self.db)
61+
if log_enabled(log):
62+
log.debug("connecting to %s:%d/%d", self.host, self.port, self.db)
6263
try:
6364
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6465
sock.settimeout(self.socket_timeout)
@@ -82,7 +83,8 @@ def disconnect(self):
8283
"Disconnects from the Redis server"
8384
if self._sock is None:
8485
return
85-
log.debug("disconnecting from %s:%d/%d", self.host, self.port, self.db)
86+
if log_enabled(log):
87+
log.debug("disconnecting from %s:%d/%d", self.host, self.port, self.db)
8688
try:
8789
self._sock.close()
8890
except socket.error:
@@ -161,6 +163,9 @@ def dict_merge(*dicts):
161163
[merged.update(d) for d in dicts]
162164
return merged
163165

166+
def log_enabled(log, level=logging.DEBUG):
167+
return log.isEnabledFor(log, level)
168+
164169
def repr_command(args):
165170
"Represents a command as a string."
166171
command = [args[0]]
@@ -338,7 +343,8 @@ def _execute_command(self, command_name, command, **options):
338343
if self.subscribed and not subscription_command:
339344
raise RedisError("Cannot issue commands other than SUBSCRIBE and "
340345
"UNSUBSCRIBE while channels are open")
341-
log.debug(repr_command(command))
346+
if log_enabled(log):
347+
log.debug(repr_command(command))
342348
command = self._encode_command(command)
343349
try:
344350
self.connection.send(command, self)
@@ -1438,7 +1444,7 @@ def _execute_transaction(self, commands):
14381444
commands,
14391445
(('', ('EXEC',), ''),)
14401446
)])
1441-
if log.isEnabledFor(logging.DEBUG):
1447+
if log_enabled(log):
14421448
log.debug("MULTI")
14431449
for command in commands:
14441450
log.debug("TRANSACTION> "+ repr_command(command[1]))
@@ -1468,7 +1474,7 @@ def _execute_transaction(self, commands):
14681474
def _execute_pipeline(self, commands):
14691475
# build up all commands into a single request to increase network perf
14701476
all_cmds = ''.join([self._encode_command(c) for _1, c, _2 in commands])
1471-
if log.isEnabledFor(logging.DEBUG):
1477+
if log_enabled(log):
14721478
for command in commands:
14731479
log.debug("PIPELINE> " + repr_command(command[1]))
14741480
self.connection.send(all_cmds, self)

0 commit comments

Comments
 (0)