Skip to content

Commit 630ebd2

Browse files
DOCSP-46811 Standardized Logger (#981)
1 parent b67206d commit 630ebd2

File tree

3 files changed

+249
-21
lines changed

3 files changed

+249
-21
lines changed

source/fundamentals/logging.txt

Lines changed: 197 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-logging:
2+
13
=======
24
Logging
35
=======
@@ -7,37 +9,212 @@ Logging
79
:values: reference
810

911
.. meta::
10-
:keywords: code example, deprecated, replace
12+
:keywords: code example, log, information, monitor
1113

1214
.. contents:: On this page
1315
:local:
1416
:backlinks: none
15-
:depth: 1
17+
:depth: 2
1618
:class: singlecols
1719

18-
.. important::
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to configure a logger in the
24+
{+driver-short+}. The driver allows you to log information categorized
25+
at following severity levels:
26+
27+
- ``emergency``
28+
- ``alert``
29+
- ``critical``
30+
- ``error``
31+
- ``warn``
32+
- ``notice``
33+
- ``info``
34+
- ``debug``
35+
- ``trace``
36+
- ``off``
37+
38+
The preceding list is ordered by decreasing severity level. Specifying a severity
39+
level also logs all messages with higher severity levels. For example, setting
40+
the log level to ``critical`` also results in log messages with severity levels of
41+
``emergency`` and ``alert``.
42+
43+
The lower the severity level you specify, the more information the driver logs,
44+
which might impact the performance of your application.
45+
46+
Configuration
47+
-------------
48+
49+
You can configure logging in the {+driver-short+} without code changes by
50+
specifying environment variables. You can also configure logging
51+
programmatically by specifying client options in the ``MongoClient``
52+
constructor.
53+
54+
.. note::
55+
56+
Because connection strings are often shared among a deployment of different
57+
appications that might have different logging support, we do not recommend
58+
using a connection string to configure logging.
59+
60+
Environment Variables
61+
~~~~~~~~~~~~~~~~~~~~~
62+
63+
You can configure logging for different components of the driver by specifying
64+
a severity level in one or more of the following environment variables:
65+
66+
- ``MONGODB_LOG_ALL``: Specifies the default severity for any unset components
67+
- ``MONGODB_LOG_COMMAND``: Logs all commands sent to the server
68+
- ``MONGODB_LOG_TOPOLOGY``: Logs any changes to the cluster topology
69+
- ``MONGODB_LOG_SERVER_SELECTION``: Logs the server selection process
70+
- ``MONGODB_LOG_CONNECTION``: Logs all connection pool events
71+
- ``MONGODB_LOG_CLIENT``: Logs all client events
72+
73+
If you don't specify any of the preceding environment variables, the driver uses
74+
the value of ``MONGODB_LOG_ALL``, which if not specified, is implicitly set to
75+
``off``.
76+
77+
.. tip::
78+
79+
Logging at the command level is the most performance-heavy logging option
80+
due to the frequency in which commands are sent to the server. Only
81+
specify this option if necessary for debugging your application.
82+
83+
The following example sets the log level for all components to ``debug`` except
84+
for ``MONGODB_LOG_COMMAND``:
85+
86+
.. code-block:: bash
87+
88+
export MONGODB_LOG_ALL="debug"
89+
export MONGODB_LOG_COMMAND="off"
90+
91+
Log Location
92+
````````````
93+
94+
You can specify whether the driver logs to ``stderr`` or ``stdout`` by setting
95+
the ``MONGODB_LOG_PATH`` environment variable to ``"stderr"`` or ``"stdout"``,
96+
as shown in the following example:
97+
98+
.. code-block:: bash
99+
100+
export MONGODB_LOG_PATH="stderr"
101+
102+
By default, the driver logs to ``stderr``.
103+
104+
Document Length
105+
```````````````
106+
107+
The driver stringifies logged documents by using EJSON, which limits strings to
108+
1000 characters by default. You can specify a maximum document length for your
109+
logger by specifying the ``MONGODB_LOG_MAX_DOCUMENT`` environment variable. Set
110+
this variable to ``0`` to not perform truncation.
111+
112+
The following example sets the maximum document length to 500 characters:
113+
114+
.. code-block:: bash
115+
116+
export MONGODB_LOG_MAX_DOCUMENT_LENGTH=500
117+
118+
Client Options
119+
~~~~~~~~~~~~~~
120+
121+
You can configure logging programmatically by specifying client options in the
122+
``MongoClient`` constructor. Because client options take precedence over environment
123+
variables, only specify them in the client if you no longer want the driver to
124+
respond to environment variables.
125+
126+
.. tip::
127+
128+
If your application relies on the format of ``stdout`` or ``stderr``, we
129+
recommend configuring logging by using client options to avoid conflicts with
130+
your application user's environment variables.
131+
132+
You can specify which component to configure logging for by specifying one or more of the
133+
following client options:
134+
135+
- ``default``: Specifies the default severity for any unset components
136+
- ``command``: Logs all commands sent to the server
137+
- ``topology``: Logs any changes to the cluster topology
138+
- ``serverSelection``: Logs the server selection process
139+
- ``connection``: Logs all connection pool events
140+
- ``client``: Logs all client events
141+
142+
To specify a log level for a component, set the
143+
``mongodbLogComponentSeverities`` option to an object that contains the
144+
component and your desired severity level. The following example sets the log
145+
level for all components to ``debug`` except for ``command``:
146+
147+
.. literalinclude:: /includes/fundamentals/logging.js
148+
:language: javascript
149+
:start-after: start-logger-client-options
150+
:end-before: end-logger-client-options
151+
152+
Log Location
153+
````````````
154+
You can specify whether the driver logs to ``stderr`` or ``stdout`` by setting
155+
the ``mongodbLogPath`` option to ``"stderr"`` or ``"stdout"``, as shown in the
156+
following example:
157+
158+
.. literalinclude:: /includes/fundamentals/logging.js
159+
:language: javascript
160+
:start-after: start-log-location
161+
:end-before: end-log-location
162+
:emphasize-lines: 5-8
163+
164+
By default, the driver logs to ``stderr``.
165+
166+
You can also specify a custom log destination. The following example creates a
167+
custom log destination:
168+
169+
.. literalinclude:: /includes/fundamentals/logging.js
170+
:language: javascript
171+
:start-after: start-custom-logger
172+
:end-before: end-custom-logger
173+
174+
If your function throws an error in the write operation, the thrown error
175+
ends the logger. Because of this, we recommend that you handle errors by
176+
making the write function a no-op rather than throwing an error, as shown in
177+
the preceding example.
178+
179+
.. note::
180+
181+
Logging can exhaust disk space if the proper log rotation system is not in
182+
place. We recommend that you connect your custom write function to a popular
183+
logging library.
184+
185+
Document Length
186+
```````````````
187+
188+
The driver stringifies logged documents by using EJSON, which limits strings to
189+
1000 characters by default. You can specify a maximum document length for your
190+
logger by specifying the ``mongodbLogMaxDocumentLength`` option. Set
191+
this option to ``0`` to perform no truncation.
19192

20-
The driver doesn't use the logger in versions 4.0 and later.
21-
Attempting to use prior logger settings in this version won't print
22-
anything in the log.
193+
The following example sets the maximum document length to 500 characters:
23194

24-
Instead, see our monitoring guides:
195+
.. literalinclude:: /includes/fundamentals/logging.js
196+
:language: javascript
197+
:start-after: start-log-length
198+
:end-before: end-log-length
199+
:emphasize-lines: 5, 8
25200

26-
- :ref:`Command Monitoring <node-command-monitoring>`
27-
- :ref:`Cluster Monitoring <node-cluster-monitoring>`
28-
- :ref:`Connection Pool Monitoring <node-connection-pool-monitoring>`
201+
Additional Information
202+
----------------------
29203

30-
Temporary Alternative
31-
---------------------
204+
For more information about monitoring with the {+driver-short+}, see the
205+
following monitoring guides:
32206

33-
We are developing a new logging framework. In the meantime, you can output monitor events
34-
by using the following snippet:
207+
- :ref:`Command Monitoring <node-command-monitoring>`
208+
- :ref:`Cluster Monitoring <node-cluster-monitoring>`
209+
- :ref:`Connection Pool Monitoring <node-connection-pool-monitoring>`
35210

36-
.. code-block:: javascript
211+
API Documentation
212+
~~~~~~~~~~~~~~~~~
37213

38-
const uri = "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
39-
const client = new MongoClient(uri, { monitorCommands:true });
214+
To learn more about any of the options or types discussed in this guide, see the
215+
following API documentaion:
40216

41-
client.on('commandStarted', (event) => console.debug(event));
42-
client.on('commandSucceeded', (event) => console.debug(event));
43-
client.on('commandFailed', (event) => console.debug(event));
217+
- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__
218+
- `mongodbLogComponentSeverities <{+api+}/interfaces/MongoClientOptions.html#mongodbLogComponentSeverities>`__
219+
- `mongodbLogMaxDocumentLength <{+api+}/interfaces/MongoClientOptions.html#mongodbLogMaxDocumentLength>`__
220+
- `mongodbLogPath <{+api+}/interfaces/MongoClientOptions.html#mongodbLogPath>`__
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// start-logger-client-options
2+
const client = new MongoClient("<connection string>", {
3+
mongodbLogComponentSeverities: {
4+
default: "debug",
5+
command: "off"
6+
}
7+
});
8+
// end-logger-client-options
9+
10+
// start-log-location
11+
const mongodbLogComponentSeverities = {
12+
default: "debug"
13+
};
14+
15+
const mongodbLogPath = "stdout";
16+
const client = new MongoClient("<connection string>",
17+
{ mongodbLogComponentSeverities, mongodbLogPath }
18+
);
19+
// end-log-location
20+
21+
// start-custom-logger
22+
import fs from 'node:fs/promises';
23+
import util from 'node:util';
24+
25+
const mongodbLogPath = {
26+
file: await fs.open(`./server-${+new Date()}.logs`, 'w'),
27+
async write(log) {
28+
try {
29+
await this.file?.appendFile(util.inspect(log) + '\n');
30+
} catch (fileError) {
31+
console.log('cannot log anymore', fileError);
32+
this.file = null;
33+
}
34+
}
35+
}
36+
37+
const client = new MongoClient("<connection string>", { mongodbLogPath });
38+
// end-custom-logger
39+
40+
// start-log-length
41+
const mongodbLogComponentSeverities = {
42+
default: "debug"
43+
};
44+
45+
const mongodbLogLength = 500;
46+
const client = new MongoClient("<connection string>", {
47+
mongodbLogComponentSeverities,
48+
mongodbLogLength
49+
});
50+
// end-log-length
51+

source/whats-new.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ The {+driver-short+} v6.13 release includes the following features:
4949

5050
env MONGODB_LOG_ALL=debug node server.mjs
5151

52-
.. TODO: To learn more, see the :ref:`Logging <node-logging>` guide.
52+
To learn more about logging, see the :ref:`Logging <node-logging>` guide.
5353

5454
- Improves command monitoring performance by removing deep copies of command and
5555
reply objects. Modifying the command and response values might lead to

0 commit comments

Comments
 (0)