OpenTelemetry PyMongo Instrumentation

0.62b0 · active · verified Thu Apr 09

This library provides automatic instrumentation for the PyMongo library, enabling OpenTelemetry to collect traces from MongoDB operations. It is part of the OpenTelemetry Python Contrib project and is currently in a beta release cycle with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry SDK with a console exporter, instrument PyMongo, and perform basic database operations. It will print the generated traces to the console.

import os
import time
from pymongo import MongoClient
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.pymongo import PymongoInstrumentor

# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "pymongo-example-service"})
tracer_provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)

# Instrument PyMongo
PymongoInstrumentor().instrument(capture_statement=True) # Set capture_statement=True to include full queries

# Connect to MongoDB (ensure a local MongoDB instance is running, e.g., via Docker)
# docker run -d -p 27017:27017 --name mongo-dev mongo:latest
client = MongoClient(os.environ.get('MONGO_URI', 'mongodb://localhost:27017/'))
db = client['testdb']
collection = db['testcollection']

print("Performing MongoDB operations...")

# Perform some operations
collection.insert_one({"name": "Alice", "age": 30})
print("Inserted one document.")

time.sleep(0.1)

result = collection.find_one({"name": "Alice"})
print(f"Found document: {result}")

time.sleep(0.1)

collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
print("Updated one document.")

time.sleep(0.1)

collection.delete_one({"name": "Alice"})
print("Deleted one document.")

# Cleanup (optional for demo, real applications manage connections)
client.close()
print("MongoDB operations complete.")

view raw JSON →