Skip to content

Redis

The logfire.instrument_redis() method will create a span for every command executed by your Redis clients.

Installation

Install logfire with the redis extra:

Terminal
pip install 'logfire[redis]'

Usage

Let’s setup a container with Redis and run a Python script that connects to the Redis server to demonstrate how to use Logfire with Redis.

Setup a Redis Server Using Docker

First, we need to initialize a Redis server. This can be easily done using Docker with the following command:

Terminal
docker run --name redis -p 6379:6379 -d redis:latest

Run the Python script

main.py
import redis

import logfire

logfire.configure()
logfire.instrument_redis()

client = redis.StrictRedis(host='localhost', port=6379)
client.set('my-key', 'my-value')


async def main():
    client = redis.asyncio.Redis(host='localhost', port=6379)
    await client.get('my-key')


if __name__ == '__main__':
    import asyncio

    asyncio.run(main())

The keyword arguments of logfire.instrument_redis() are passed to the RedisInstrumentor().instrument() method of the OpenTelemetry Redis Instrumentation package, read more about it here.

API Reference

instrument_redis

def instrument_redis(
    capture_statement: bool = False,
    request_hook: RedisRequestHook | None = None,
    response_hook: RedisResponseHook | None = None,
    kwargs: Any = {},
) -> None

Instrument the redis module so that spans are automatically created for each operation.

Uses the OpenTelemetry Redis Instrumentation library, specifically RedisInstrumentor().instrument(), to which it passes **kwargs.

Returns

None

Parameters

capture_statement : bool Default: False

Set to True to capture the statement in the span attributes.

request_hook : RedisRequestHook | None Default: None

A function that is called before performing the request.

response_hook : RedisResponseHook | None Default: None

A function that is called after receiving the response.

**kwargs : Any Default: \{\}

Additional keyword arguments to pass to the OpenTelemetry instrument methods for future compatibility.

RequestHook

Bases: Protocol

A hook that is called before the request is sent.

Methods
__call__
def __call__(span: Span, instance: Connection, args: Any = (), kwargs: Any = {}) -> None

Call the hook.

Returns

None

Parameters

span : Span

The span that is being created.

instance : Connection

The connection instance.

*args : Any Default: ()

The arguments that are passed to the command.

**kwargs : Any Default: \{\}

The keyword arguments that are passed to the command.

ResponseHook

Bases: Protocol

A hook that is called after the response is received.

Methods
__call__
def __call__(span: Span, instance: Connection, response: Any) -> None

Call the hook.

Returns

None

Parameters

span : Span

The span that is being created.

instance : Connection

The connection instance.

response : Any

The response that is received.