Skip to content

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.

What you’ll capture

  • 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)

Before you start

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.

Installation

Install logfire with the pymongo extra:

Terminal
pip install 'logfire[pymongo]'

Usage

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:

Terminal
docker run --name mongo -p 127.0.0.1:27017:27017 -d mongo:latest
main.py
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()

Run it with python main.py.

Verify it worked

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.

Troubleshooting

Not seeing your operations in Logfire? Check these first:

  • logfire.configure() runs before logfire.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 the LOGFIRE_TOKEN environment variable. See Getting Started.
  • You actually ran an operation. Spans appear only after a command executes.

Advanced

Capturing the command

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).

Passing options to the OpenTelemetry instrumentor

logfire.instrument_pymongo() accepts additional keyword arguments and passes them to the OpenTelemetry PyMongo instrumentation. See their documentation for the full list.

Reference

instrument_pymongo

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.

Returns

None

Parameters

capture_statement : bool Default: False

Set to True to capture the statement in the span attributes.

request_hook : Callable[[Span, CommandStartedEvent], None] | None Default: None

A function called when a command is sent to the server.

response_hook : Callable[[Span, CommandSucceededEvent], None] | None Default: None

A function that is called when a command is successfully completed.

failed_hook : Callable[[Span, CommandFailedEvent], None] | None Default: None

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.