Skip to content

Improve pika instrumentation examples #3390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 2, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -60,23 +59,50 @@

.. 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
and the third parameter is the message properties

.. 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:
Expand Down