redis / redis-py

Redis Python client
MIT License
12.58k stars 2.51k forks source link

Make it easy to log request/responses #2854

Open dblock opened 1 year ago

dblock commented 1 year ago

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?

ljluestc commented 3 months ago
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}")