OpenTelemetry Pika Instrumentation
This library provides OpenTelemetry instrumentation for the `pika` Python library, enabling automatic tracing of RabbitMQ interactions. It is part of the `opentelemetry-python-contrib` project, which frequently releases beta versions, with stable releases typically occurring less often. The library requires Python 3.9 or newer.
Warnings
- gotcha OpenTelemetry Python SDK and instrumentations must be initialized before the instrumented library (pika) is imported or used. Importing pika before calling `PikaInstrumentor().instrument()` may result in uninstrumented operations.
- breaking As a beta library (`0.x.y.b0` versioning), `opentelemetry-instrumentation-pika` may introduce breaking changes to its API, configuration, or generated telemetry attributes between minor versions. While efforts are made to align with semantic conventions, these can evolve rapidly.
- gotcha Automatic instrumentation in multi-process/forking environments (e.g., Gunicorn with multiple workers) can be problematic. OpenTelemetry SDK components, especially `PeriodicExportingMetricReader`, may not function correctly across forked processes due to issues with background threads and locks.
- gotcha The instrumentation relies on `pika` being installed and compatible. Recent changes to dependency checks mean that if `pika` is missing or its version is outside the supported range, instrumentation might fail silently or raise an `ImportError` or `DependencyConflictError`.
Install
-
pip install opentelemetry-instrumentation-pika opentelemetry-sdk pika
Imports
- PikaInstrumentor
from opentelemetry.instrumentation.pika import PikaInstrumentor
Quickstart
import pika
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.pika import PikaInstrumentor
# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "pika-test-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
# Instrument Pika
PikaInstrumentor().instrument()
# Pika usage (example: publish a message)
def send_message():
print("Sending message...")
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body=b'Hello World!')
print("Message sent.")
connection.close()
if __name__ == "__main__":
# Ensure RabbitMQ is running or adjust connection parameters
try:
send_message()
print("Traces should be printed to the console.")
except Exception as e:
print(f"Error connecting to RabbitMQ or sending message: {e}")
print("Please ensure RabbitMQ is running and accessible at 'localhost'.")