How to Set Up Logging in MongoDB: Syntax and Examples
To set up logging in MongoDB, configure the
systemLog section in the mongod.conf file, specifying the destination, path, and logLevel. Then restart the MongoDB server to apply the changes and start logging as configured.Syntax
The logging configuration in MongoDB is done in the mongod.conf file under the systemLog section. Key options include:
- destination: Where logs are sent, e.g.,
fileorconsole. - path: File path for log storage when destination is
file. - logAppend: Whether to append to existing log file (
true) or overwrite (false). - logLevel: Verbosity level from 0 (default) to 5 (most verbose).
yaml
systemLog: destination: file path: /var/log/mongodb/mongod.log logAppend: true logLevel: 1
Example
This example shows how to configure MongoDB to log to a file with verbose level 2 and append logs instead of overwriting.
yaml
systemLog: destination: file path: /var/log/mongodb/mongod.log logAppend: true logLevel: 2
Output
2024-06-01T12:00:00.000+0000 I CONTROL [initandlisten] MongoDB starting : pid=12345 port=27017 dbpath=/data/db 64-bit host=server
2024-06-01T12:00:00.001+0000 I CONTROL [initandlisten] options: { systemLog: { destination: "file", path: "/var/log/mongodb/mongod.log", logAppend: true, logLevel: 2 } }
Common Pitfalls
Common mistakes when setting up MongoDB logging include:
- Not restarting the
mongodservice after changingmongod.conf, so changes don't take effect. - Setting
destinationtofilebut not specifying a validpath, causing logging to fail. - Using too high
logLevelin production, which can generate large log files and affect performance. - Incorrect file permissions on the log file path, preventing MongoDB from writing logs.
yaml
Incorrect example: systemLog: destination: file logLevel: 3 # Missing 'path' causes no logs to be saved to file. Correct example: systemLog: destination: file path: /var/log/mongodb/mongod.log logLevel: 3
Quick Reference
| Option | Description | Example Value |
|---|---|---|
| destination | Where logs are sent | "file" or "console" |
| path | File path for logs (required if destination is file) | "/var/log/mongodb/mongod.log" |
| logAppend | Append to existing log file if true | true |
| logLevel | Verbosity level (0-5) | 1 |
| component | Set log level per component (optional advanced) | systemLog.component.accessControl=2 |
Key Takeaways
Configure logging in the mongod.conf file under the systemLog section.
Always specify a valid log file path when logging to a file.
Restart the mongod service after changing logging settings.
Use appropriate logLevel to balance detail and performance.
Check file permissions to ensure MongoDB can write logs.