From 6ba413ffad2864b4ba232e0a88248db69c2d8249 Mon Sep 17 00:00:00 2001 From: Andre Murbach Maidl Date: Fri, 28 Mar 2025 13:51:39 -0300 Subject: [PATCH] Improve pika instrumentation examples --- .../instrumentation/pika/__init__.py | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py index d9cec06525..d6b0d85686 100644 --- a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py @@ -51,7 +51,6 @@ pika_instrumentation = PikaInstrumentor() pika_instrumentation.instrument_channel(channel=channel) - channel.basic_publish(exchange='', routing_key='hello', body=b'Hello World!') pika_instrumentation.uninstrument_channel(channel=channel) @@ -60,8 +59,22 @@ .. code-block:: python + import pika + from opentelemetry.instrumentation.pika import PikaInstrumentor + from opentelemetry.trace import get_tracer_provider + + connection = pika.BlockingConnection(pika.URLParameters('amqp://localhost')) + channel = connection.channel() + tracer_provider = get_tracer_provider() + + channel.queue_declare(queue='hello') + PikaInstrumentor.instrument_channel(channel, tracer_provider=tracer_provider) + channel.basic_publish(exchange='', routing_key='hello', body=b'Hello World!') + + PikaInstrumentor.uninstrument_channel(channel) + * PikaInstrumentor also supports instrumenting with hooks that will be called when producing or consuming a message. The hooks should be of type "Callable[[Span, bytes, BasicProperties], None]" where the first parameter is the span, the second parameter is the message body @@ -69,14 +82,27 @@ .. code-block:: python + import pika + from opentelemetry.instrumentation.pika import PikaInstrumentor + from opentelemetry.trace import Span + from pika import BasicProperties + def publish_hook(span: Span, body: bytes, properties: BasicProperties): span.set_attribute("messaging.payload", body.decode()) def consume_hook(span: Span, body: bytes, properties: BasicProperties): span.set_attribute("messaging.id", properties.message_id) + connection = pika.BlockingConnection(pika.URLParameters('amqp://localhost')) + channel = connection.channel() + channel.queue_declare(queue='hello') + PikaInstrumentor.instrument_channel(channel, publish_hook=publish_hook, consume_hook=consume_hook) + channel.basic_publish(exchange='', routing_key='hello', body=b'Hello World!') + + PikaInstrumentor.uninstrument_channel(channel) + Consumer Instrumentation ------------------------ For consumer instrumentation, pika supports two consuming modes: