Docs Menu

Logging

In this guide, you can learn how to configure logging options for different PyMongo components.

PyMongo supports Python's native logging library. You can configure the logging verbosity for the following components:

  • pymongo.command, which logs command operations

  • pymongo.connection, which logs connection management operations

  • pymongo.serverSelection, which logs server selection operations

In addition to configuring these options individually, you can configure the global logging level by setting the log level on pymongo. To learn more about the native logging library, see the Python logging library documentation.

The following example sets the global logging level to INFO:

import logging
logging.getLogger("pymongo").setLevel(logging.INFO)

The following example sets the log level on the pymongo.command component to DEBUG:

import logging
logging.getLogger("pymongo.command").setLevel(logging.DEBUG)

Messages that the driver outputs will have the log level specified at the beginning of the message, as shown by this example DEBUG message:

DEBUG:pymongo.command:{"clientId": {"$oid": "..."}, "message": "Command started", "command": "{\"insert\": \"test\", \"ordered\": true, \"lsid\": {\"id\": {\"$binary\": {\"base64\": \"...\", \"subType\": \"04\"}}}, \"$db\": \"db\", \"documents\": [{\"x\": 1, \"_id\": {\"$oid\": \"...\"}}]}", "commandName": "insert", "databaseName": "db", "requestId": ..., "operationId": ..., "driverConnectionId": 1, "serverConnectionId": 3554, "serverHost": "localhost", "serverPort": 27017}

If you enable logging for the pymongo.command component, the resulting logs will be truncated after 1000 bytes by default. You can configure this truncation limit by setting the MONGODB_LOG_MAX_DOCUMENT_LENGTH environment variable to your desired length, as shown in the following example:

import os
os.environ["MONGODB_LOG_MAX_DOCUMENT_LENGTH"] = "2000"