OpenTelemetry pymongo Instrumentation
The integration with MongoDB supports the pymongo library, it can be
enabled using the PymongoInstrumentor.
Usage
from pymongo import MongoClient
from opentelemetry.instrumentation.pymongo import PymongoInstrumentor
PymongoInstrumentor().instrument()
client = MongoClient()
db = client["MongoDB_Database"]
collection = db["MongoDB_Collection"]
collection.find_one()
API
The instrument method accepts the following keyword args:
tracer_provider (
TracerProvider) - an optional tracer providerrequest_hook (
Callable[[Span, CommandStartedEvent], None]) - a function with extra user-defined logic to be performed before querying mongodbresponse_hook (
Callable[[Span, CommandSucceededEvent], None]) - a function with extra user-defined logic to be performed after the query returns with a successful responsefailed_hook (
Callable[[Span, CommandFailedEvent], None]) - a function with extra user-defined logic to be performed after the query returns with a failed responsecapture_statement (
bool) - an optional value to enable capturing the database statement that is being executed
for example:
from opentelemetry.instrumentation.pymongo import PymongoInstrumentor
from pymongo import MongoClient
def request_hook(span, event):
# request hook logic
pass
def response_hook(span, event):
# response hook logic
pass
def failed_hook(span, event):
# failed hook logic
pass
# Instrument pymongo with hooks
PymongoInstrumentor().instrument(request_hook=request_hook, response_hook=response_hook, failed_hook=failed_hook)
# This will create a span with pymongo specific attributes, including custom attributes added from the hooks
client = MongoClient()
db = client["MongoDB_Database"]
collection = db["MongoDB_Collection"]
collection.find_one()
- class opentelemetry.instrumentation.pymongo.CommandTracer(tracer, request_hook=<function dummy_callback>, response_hook=<function dummy_callback>, failed_hook=<function dummy_callback>, capture_statement=False)[source]
Bases:
CommandListener
- class opentelemetry.instrumentation.pymongo.PymongoInstrumentor(*args, **kwargs)[source]
Bases:
BaseInstrumentor- instrumentation_dependencies()[source]
Return a list of python packages with versions that the will be instrumented.
The format should be the same as used in requirements.txt or pyproject.toml.
For example, if an instrumentation instruments requests 1.x, this method should look like: :rtype:
Collection[str]- def instrumentation_dependencies(self) -> Collection[str]:
return [‘requests ~= 1.0’]
This will ensure that the instrumentation will only be used when the specified library is present in the environment.