PyMongo
See every operation your app runs against MongoDB through PyMongo (the command, how long it took, and which ones failed) as a span (one unit of work with a name, a start, and a duration) in Logfire. Related spans link together into a trace (the full journey of one request), so a slow lookup shows up right next to the code that triggered it.
- Each operation (insert, find, update, and so on) as a span, with its duration and any errors
- The collection and database the operation ran against
- Optionally, the command itself (off by default; see below)
You’ll need a Logfire project. Open Add data in your project (top navigation) and follow the
setup for your language: it signs your machine in with logfire auth (a browser sign-in, no token
to copy) and, for production or other languages, creates a write token (the credential your app
uses to send data). New to Logfire? Start with Getting Started.
Install logfire with the pymongo extra:
pip install 'logfire[pymongo]'
uv add 'logfire[pymongo]'
Add two lines to your app: logfire.configure() to connect to your project, and
logfire.instrument_pymongo() to record every operation.
The example below connects to a local MongoDB instance. If you don’t have one running, you can start one with Docker:
docker run --name mongo -p 127.0.0.1:27017:27017 -d mongo:latest
from pymongo import MongoClient
import logfire
logfire.configure()
logfire.instrument_pymongo()
client = MongoClient()
db = client['database']
collection = db['collection']
collection.insert_one({'name': 'MongoDB'})
collection.find_one()
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
import logfire
logfire.configure()
logfire.instrument_pymongo()
async def main():
client = AsyncIOMotorClient()
db = client['database']
collection = db['collection']
await collection.insert_one({'name': 'MongoDB'})
await collection.find_one()
asyncio.run(main())
Run it with python main.py.
Run your program, then open your project in the Logfire web app and go to the Live view. Within a few seconds you should see a span for each operation the script ran. Click one to see the collection and how long it took.
Not seeing your operations in Logfire? Check these first:
logfire.configure()runs beforelogfire.instrument_pymongo(). Configure the connection first, then instrument.- You call
instrument_pymongo()exactly once. - Your write token is set. In local development, run
logfire projects use <your-project>; in production, set theLOGFIRE_TOKENenvironment variable. See Getting Started. - You actually ran an operation. Spans appear only after a command executes.
By default, the command sent to MongoDB isn’t recorded, since it can contain sensitive data. To
include it, pass capture_statement=True:
import logfire
logfire.configure()
logfire.instrument_pymongo(capture_statement=True)
Turning this on sends the command (including any values in it) to Logfire, so avoid it if your queries carry secrets or personally identifiable information (PII).
logfire.instrument_pymongo() accepts additional keyword
arguments and passes them to the OpenTelemetry PyMongo instrumentation. See
their documentation for the full list.
- Underlying OpenTelemetry package: PyMongo instrumentation
def instrument_pymongo(
capture_statement: bool = False,
request_hook: Callable[[Span, CommandStartedEvent], None] | None = None,
response_hook: Callable[[Span, CommandSucceededEvent], None] | None = None,
failed_hook: Callable[[Span, CommandFailedEvent], None] | None = None,
**kwargs: Any,
) -> None
Instrument the pymongo module so that spans are automatically created for each operation.
Uses the
OpenTelemetry pymongo Instrumentation
library, specifically PymongoInstrumentor().instrument(), to which it passes **kwargs.
capture_statement : bool Default: False
Set to True to capture the statement in the span attributes.
A function called when a command is sent to the server.
A function that is called when a command is successfully completed.
A function that is called when a command fails.
**kwargs : Any Default: {}
Additional keyword arguments to pass to the OpenTelemetry instrument methods for future compatibility.