Practical Monitoring Techniques
Comprehensive Monitoring Approach
graph TD
A[Practical Monitoring] --> B[Logging]
A --> C[Performance Metrics]
A --> D[Error Tracking]
A --> E[Automated Alerts]
Logging Connection Events
Python Logging Implementation
import logging
import pymongo
from pymongo import MongoClient
class MongoConnectionLogger:
def __init__(self, connection_string):
## Configure logging
logging.basicConfig(
filename='mongodb_connection.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
self.client = None
self.connection_string = connection_string
def connect(self):
try:
self.client = MongoClient(self.connection_string)
logging.info(f"Successfully connected to MongoDB")
return self.client
except Exception as e:
logging.error(f"Connection failed: {e}")
return None
def close_connection(self):
if self.client:
self.client.close()
logging.info("MongoDB connection closed")
Connection Pool Metrics
Metric |
Description |
Monitoring Approach |
Active Connections |
Current open connections |
Track connection count |
Connection Utilization |
Percentage of used connections |
Monitor pool saturation |
Connection Latency |
Time to establish connection |
Measure response times |
Error Tracking and Handling
def monitor_connection_errors(connection_string, max_retries=3):
retries = 0
while retries < max_retries:
try:
client = MongoClient(connection_string)
client.admin.command('ismaster')
return client
except pymongo.errors.ConnectionFailure as e:
retries += 1
print(f"Connection attempt {retries} failed: {e}")
time.sleep(2) ## Wait before retry
raise Exception("Maximum connection attempts exceeded")
Automated Monitoring Script
import schedule
import time
import pymongo
def check_mongodb_status(connection_string):
try:
client = MongoClient(connection_string)
## Check server status
status = client.admin.command('serverStatus')
## Log critical metrics
print(f"Active Connections: {status['connections']['current']}")
print(f"Uptime: {status['uptime']} seconds")
client.close()
except Exception as e:
print(f"Monitoring error: {e}")
## Schedule monitoring
schedule.every(5).minutes.do(
check_mongodb_status,
'mongodb://localhost:27017'
)
## Run scheduled tasks
while True:
schedule.run_pending()
time.sleep(1)
-
Native MongoDB Tools
- MongoDB Compass
- MongoDB Logs
- Database Profiler
-
External Monitoring Solutions
- Prometheus
- Grafana
- ELK Stack
Best Practices
- Implement comprehensive logging
- Set up automated monitoring scripts
- Configure connection pool settings
- Create alert mechanisms
- Regularly review connection performance
By applying these practical monitoring techniques, developers can ensure robust and reliable MongoDB connections in their LabEx environments.