Technology Encyclopedia Home >How to obtain slow logs of MongoDB instances?

How to obtain slow logs of MongoDB instances?

To obtain slow logs of MongoDB instances, you can follow these steps:

  1. Enable Slow Query Logging:
    MongoDB records slow queries in its log files if the slowms threshold is exceeded. By default, queries taking longer than 100 milliseconds are logged. You can adjust this threshold in the MongoDB configuration file (mongod.conf) or dynamically via the setParameter command.

    Example (in mongod.conf):

    operationProfiling:
      mode: slowOp
      slowOpThresholdMs: 100  # Adjust the threshold as needed
    

    Example (dynamic command):

    db.adminCommand({ setParameter: 1, slowms: 50 })  // Set threshold to 50ms
    
  2. Access the Log Files:
    Slow queries are logged to MongoDB's standard log file. The location of the log file depends on your deployment:

    • Standalone or Replica Set: Check the logpath setting in mongod.conf.
    • MongoDB Atlas: Slow logs are available in the Atlas UI under Database > Performance Advisor or via the Atlas API.

    Example (viewing logs):

    tail -f /var/log/mongodb/mongod.log  # Replace with your actual log path
    
  3. Use MongoDB Tools for Analysis:

    • mongostat and mongotop: Monitor real-time performance and identify slow operations.
    • MongoDB Compass: Provides a GUI to analyze query performance.
  4. Cloud-Specific Solutions (e.g., Tencent Cloud):
    If you're using Tencent Cloud Database for MongoDB, slow logs are automatically collected and can be accessed via the Tencent Cloud Console under Database > Log Management. You can also export logs to Tencent Cloud CLS (Cloud Log Service) for advanced analysis and alerting.

Example (Tencent Cloud CLI):

tccli mongodb DescribeSlowLogs --InstanceId <your-instance-id> --StartTime <start-time> --EndTime <end-time>

This retrieves slow logs for a specified time range.