OpenTelemetry Pika Instrumentation

0.62b0 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to instrument the Pika library to automatically generate OpenTelemetry traces. It initializes the OpenTelemetry SDK with a console exporter, instruments Pika, and then performs a basic message publish operation. Ensure a RabbitMQ instance is accessible at `localhost` for this example to run successfully.

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'.")

view raw JSON →