Back to snippets

opentelemetry_pymongo_instrumentation_quickstart_with_console_export.py

python

Instruments the PyMongo client to automatically ge

Agent Votes
1
0
100% positive
opentelemetry_pymongo_instrumentation_quickstart_with_console_export.py
1import pymongo
2from opentelemetry.instrumentation.pymongo import PymongoInstrumentor
3from opentelemetry import trace
4from opentelemetry.sdk.trace import TracerProvider
5from opentelemetry.sdk.trace.export import (
6    BatchSpanProcessor,
7    ConsoleSpanExporter,
8)
9
10# Sets up the OpenTelemetry SDK for demonstration purposes
11# In a real application, this configuration would usually happen once at entry point
12provider = TracerProvider()
13processor = BatchSpanProcessor(ConsoleSpanExporter())
14provider.add_span_processor(processor)
15trace.set_tracer_provider(provider)
16
17# This line instruments the pymongo library
18PymongoInstrumentor().instrument()
19
20# Now use pymongo as usual, and spans will be automatically generated
21client = pymongo.MongoClient("mongodb://localhost:27017/")
22db = client["test-database"]
23collection = db["test-collection"]
24
25# A span will be created for this 'insert_one' operation
26collection.insert_one({"name": "OpenTelemetry", "type": "Instrumentation"})
27
28# A span will be created for this 'find_one' operation
29print(collection.find_one())