Make it easy to log request/responses
Version: What redis-py and what redis version is the issue happening on?
Redis-py 4.6.0 Redis 6.2.10
Platform: What platform / version? (For example Python 3.5.1 on Windows 7 / Ubuntu 15.10 / Azure)
MacOS
Description: Description of your issue, stack traces from errors and code that reproduces the issue
I'd like to log request/responses from the client (and can't find how to do it after trying very hard ;)). Looking for equivalent functionality of httpx:
def log_request(request):
print(f"> {request.method} {request.url}")
def log_response(response):
request = response.request
print(f"< {request.method} {request.url} - {response.status_code}")
def main():
client = Client(
...
event_hooks={
"request": [log_request],
"response": [log_response],
},
)
Is there a way to achieve this with redis-py, otherwise wdyt about adding a feature that makes this easy?
import logging
import redis
# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('redis')
# Set up the connection pool and Redis client
rdb = redis.ConnectionPool(
connection_class=redis.UnixDomainSocketConnection,
path="/path/redis/redis.sock",
socket_timeout=5 # Setting the socket timeout
)
r = redis.Redis(connection_pool=rdb)
# Example function to log Redis commands
def log_redis_command(command, *args, **kwargs):
logger.debug(f"Executing command: {command}, args: {args}, kwargs: {kwargs}")
# Wrapper function to log commands
def execute_command_with_logging(redis_client, command, *args, **kwargs):
log_redis_command(command, *args, **kwargs)
response = redis_client.execute_command(command, *args, **kwargs)
logger.debug(f"Response: {response}")
return response
# Example usage
try:
# Log and execute a GET command
result = execute_command_with_logging(r, "GET", "users:1234")
if result:
print(result.decode('utf-8'))
else:
print("Key not found.")
except redis.exceptions.RedisError as e:
logger.error(f"Redis error: {e}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
This is great, on high loaded Redis server you can't easily use MONITOR command.
Why doesn't this issue receive more support/comments?
Maybe the alternative is https://redis-py.readthedocs.io/en/stable/opentelemetry.html ?
Why doesn't this issue receive more support/comments?
Redis was no longer open-source?