MongoDB provides various types of logs to help developers debug any issues or track activities. You can use them to track all kinds of events such as server status, query execution, etc.
Here’s a basic way to manage logs in MongoDB:
1. Configuration:
The MongoDB configuration file, named `mongod.conf`, contains options to control the MongoDB instance. The log settings can be managed in this file under `systemLog:`. Example: \`\`\` systemLog: destination: file path: “/var/log/mongodb/mongod.log“ logAppend: true \`\`\` `destination` sets where to output log messages, `path` sets the log file path and `logAppend` controls whether MongoDB appends new messages to the end of the existing log file.1. Accessing Logs:
Based on the path you provided in the configuration, you can directly view the log file. Using Linux, simply do: \`\`\` cat /var/log/mongodb/mongod.log \`\`\`1. Changing Log Verbosity:
You may wish to change the verbosity level of the log. Higher levels increase the number of messages. You can do this by running these commands in MongoDB shell: \`\`\` db.setLogLevel(1) db.setLogLevel(2) \`\`\` Here, `1` is for only errors, `2` for warnings too and goes on.1. View Logs from MongoDB shell:
You can directly view the recent logs from the MongoDB shell by running: \`\`\` db.adminCommand({ getLog : “\*” }) db.adminCommand({ getLog : “global” }) \`\`\`1. Rotating Logs:
If the log files grow large, you can rotate the logs which archives the current log and start a new log. To rotate logs: \`\`\` db.runCommand( { logRotate : 1 } ) \`\`\`Remember to replace the file paths and log levels as per your configuration.