OpenTelemetry Redis Instrumentation

0.61b0 · active · verified Mon Apr 06

The `opentelemetry-instrumentation-redis` library provides automatic instrumentation for the Python `redis` client, capturing Redis commands as OpenTelemetry spans. It is part of the `opentelemetry-python-contrib` project and is currently in a beta state, with the latest version being 0.61b0. New versions are released as part of the broader OpenTelemetry Python Contrib release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with the Redis instrumentation. It configures a simple `TracerProvider` with a `ConsoleSpanExporter` (for demonstration purposes), then enables Redis instrumentation globally using `RedisInstrumentor().instrument()`. Any subsequent Redis client operations will generate spans. Ensure a Redis server is running at `localhost:6379` or configure environment variables `REDIS_HOST` and `REDIS_PORT`.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.instrumentation.redis import RedisInstrumentor
import redis

# 1. Configure OpenTelemetry TracerProvider
resource = Resource.create({"service.name": os.environ.get('OTEL_SERVICE_NAME', 'redis-app')})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(
    BatchSpanProcessor(ConsoleSpanExporter())
)
trace.set_tracer_provider(tracer_provider)

# 2. Instrument Redis
RedisInstrumentor().instrument()

# 3. Use Redis client (operations will be traced)
try:
    client = redis.StrictRedis(host=os.environ.get('REDIS_HOST', 'localhost'), port=int(os.environ.get('REDIS_PORT', 6379)), db=0)
    client.ping()
    print("Successfully connected to Redis.")
    client.set("mykey", "myvalue")
    value = client.get("mykey")
    print(f"Retrieved from Redis: {value.decode('utf-8')}")
    client.delete("mykey")
except redis.exceptions.ConnectionError as e:
    print(f"Could not connect to Redis: {e}. Please ensure Redis is running.")

# Example of suppressing instrumentation for a specific call
# from opentelemetry.instrumentation.utils import suppress_instrumentation
# with suppress_instrumentation():
#     client.get("untraced-key")

view raw JSON →