Skip to content

Commit 133d45a

Browse files
authored
DOCSP-30549: tracing and logging (#14)
1 parent 3c93124 commit 133d45a

File tree

6 files changed

+299
-3
lines changed

6 files changed

+299
-3
lines changed

snooty.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,6 @@ docs-branch = "master" # always set this to the docs branch (i.e. master, v2.6,
2121
version = "2.6.0" # always set this to the driver version (i.e. 2.6.0, 2.5.0, etc.)
2222
min-rust-version = "1.57" # always set this to the minimum supported Rust version
2323
api = "https://docs.rs/mongodb/{+version+}/mongodb"
24-
stable-api = "Stable API"
24+
stable-api = "Stable API"
25+
tracing-version = "0.1.37"
26+
tracing-sub-version = "0.3.17"

source/fundamentals.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Fundamentals
1111
/fundamentals/connections
1212
/fundamentals/crud
1313
/fundamentals/aggregation
14+
/fundamentals/tracing-logging
1415
/fundamentals/run-command
1516

1617
..
@@ -22,7 +23,6 @@ Fundamentals
2223
/fundamentals/bson
2324
/fundamentals/indexes
2425
/fundamentals/transactions
25-
/fundamentals/logging
2626
/fundamentals/collations
2727
/fundamentals/monitoring
2828
/fundamentals/gridfs
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
.. _rust-tracing-logging:
2+
3+
=================
4+
Tracing & Logging
5+
=================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to use the {+driver-short+} to configure
17+
**tracing** and **logging** for your application. Tracing and logging
18+
are two frameworks for observing your application. Logging allows you to
19+
view a discrete, event-based log of driver activities, while tracing
20+
provides a continuous view. Logs might help you identify an issue in
21+
your application, while a trace might help you locate the reason for the
22+
issue.
23+
24+
In the {+driver-short+}, the functionalities of tracing and logging do not
25+
differ greatly. However, when you enable tracing, the driver emits messages in a
26+
more structured format, which can make it easier for your application to
27+
consume event messages programmatically.
28+
29+
Tracers and loggers log messages at a severity, or verbosity, level that you
30+
can specify. By enabling one of these components in your application,
31+
you can receive information about your application's activities at a
32+
high level, a detailed level, or somewhere in between.
33+
34+
.. tip::
35+
36+
To learn more about logging severity levels, see the Wikipedia entry on
37+
the :wikipedia:`Syslog standard for message logging <Syslog#Severity_level>`.
38+
39+
Enable Tracing and Logging
40+
--------------------------
41+
42+
The driver implements the `tracing <https://crates.io/crates/tracing>`__
43+
crate to enable the driver to emit messages for driver events.
44+
45+
.. important:: tracing Crate is Unstable
46+
47+
Since the ``tracing`` crate currently does not have a 1.0 version
48+
release, you should consider the functionality to be unstable.
49+
50+
To enable tracing, logging, or both, you must add the ``tracing``
51+
dependency and the ``tracing-unstable`` feature flag to your ``mongodb``
52+
dependency in your ``Cargo.toml`` file:
53+
54+
.. code-block:: none
55+
:emphasize-lines: 2, 6
56+
57+
[dependencies]
58+
tracing = "{+tracing-version+}"
59+
60+
[dependencies.mongodb]
61+
version = "{+version+}"
62+
features = ["tracing-unstable"]
63+
64+
The following table describes components that you can emit events
65+
against and their corresponding targets:
66+
67+
.. list-table::
68+
:widths: 25 25 50
69+
:header-rows: 1
70+
71+
* - Component
72+
- Target
73+
- Description
74+
75+
* - Command
76+
- ``mongodb::command``
77+
- Events describe commands sent to the database and whether they
78+
succeed or fail.
79+
80+
* - Server selection
81+
- ``mongodb::server_selection``
82+
- Events describe the driver's process of selecting a server in a
83+
MongoDB deployment.
84+
85+
* - Connection
86+
- ``mongodb::connection``
87+
- Events describe the behavior of driver connection pools and the
88+
connections they contain.
89+
90+
To specify the logging component and severity level, you can set the
91+
``RUST_LOG`` environment variable when you compile and run your
92+
application. Specify the logging component by setting the value of
93+
``RUST_LOG`` to one of the targets provided in the preceding table,
94+
along with a severity level.
95+
96+
The following code shows a command to execute a program that records
97+
connection events at the ``debug`` level:
98+
99+
.. code-block:: bash
100+
101+
$ RUST_LOG='mongodb::connection=debug' cargo run
102+
103+
The following sections describe how to consume events using either
104+
:ref:`tracing <rust-tracing>` or :ref:`logging <rust-logging>`.
105+
106+
.. _rust-tracing:
107+
108+
Implement Tracing
109+
-----------------
110+
111+
To enable tracing, you must also add the ``tracing-subscriber``
112+
dependency to your ``Cargo.toml`` file. The following code shows a
113+
sample dependencies list that contains the driver dependencies and the
114+
``tracing-subscriber`` crate:
115+
116+
.. code-block:: none
117+
:emphasize-lines: 3
118+
119+
[dependencies]
120+
tracing = "{+tracing-version+}"
121+
tracing-subscriber = "{+tracing-sub-version+}"
122+
123+
[dependencies.mongodb]
124+
version = "{+version+}"
125+
features = ["tracing-unstable"]
126+
127+
Then, in your application, you must register a type implementing the
128+
``tracing::Subscriber`` trait to consume events with tracing. The
129+
following code shows how to register a tracing subscriber that uses the
130+
specifications of the ``RUST_LOG`` environment variable:
131+
132+
.. literalinclude:: /includes/fundamentals/code-snippets/tracing.rs
133+
:start-after: begin-subscriber
134+
:end-before: end-subscriber
135+
:language: rust
136+
:dedent:
137+
138+
.. tip::
139+
140+
To learn more about registering a subscriber, see the ``tracing``
141+
`documentation <https://docs.rs/tracing/latest/tracing/#in-executables>`__.
142+
143+
If you run your application and trace against commands at the ``debug``
144+
level, the driver emits messages whenever you execute an operation. The
145+
following code shows the command for this tracing specification:
146+
147+
.. code-block:: bash
148+
149+
$ RUST_LOG='mongodb::command=debug' cargo run
150+
151+
With ``debug`` level tracing specified, when you perform a write
152+
operation, the driver generates trace messages:
153+
154+
.. io-code-block::
155+
:copyable: false
156+
157+
.. input:: /includes/fundamentals/code-snippets/tracing.rs
158+
:language: rust
159+
:dedent:
160+
:start-after: start-operation
161+
:end-before: end-operation
162+
163+
.. output::
164+
:language: console
165+
:visible: false
166+
167+
2023-07-21T17:37:13.587794Z DEBUG mongodb::command: Command started topologyId="..." command="{\"insert\":\"test_coll\", ...}" databaseName="test" commandName="insert" requestId=12 driverConnectionId=1 serverConnectionId=133839 serverHost="..." serverPort=27017
168+
2023-07-21T17:37:13.630401Z DEBUG mongodb::command: Command succeeded topologyId="..." reply="{\"n\":1, ...}" commandName="insert" requestId=12 driverConnectionId=1 serverConnectionId=133839 serverHost="..." serverPort=27017 durationMS=42
169+
170+
.. _rust-logging:
171+
172+
Implement Logging
173+
-----------------
174+
175+
To enable logging, you must also add the ``log`` or ``log-always`` feature
176+
flag to the ``tracing`` dependency in your ``Cargo.toml`` file. You also
177+
need to add a dependency for a logging crate, such as ``env_logger``:
178+
179+
.. code-block:: none
180+
:emphasize-lines: 2-3
181+
182+
[dependencies]
183+
tracing = { version = "{+tracing-version+}", features = ["log"] }
184+
env_logger = "0.10.0"
185+
186+
[dependencies.mongodb]
187+
version = "{+version+}"
188+
features = ["tracing-unstable"]
189+
190+
.. tip::
191+
192+
To learn more about the ``log`` and ``log-always`` flags, see the
193+
``tracing`` `documentation <https://docs.rs/tracing/latest/tracing/#emitting-log-records>`__.
194+
195+
To learn more about the third-party logging crate ``env_logger``, see
196+
its `documentation <https://crates.io/crates/env_logger>`__.
197+
198+
Then, in your application, you must register a global logger to consume
199+
events with logging. The following code shows how to register a logger
200+
that uses the specifications of the ``RUST_LOG`` environment variable:
201+
202+
.. literalinclude:: /includes/fundamentals/code-snippets/logging.rs
203+
:start-after: begin-logger
204+
:end-before: end-logger
205+
:language: rust
206+
:dedent:
207+
208+
.. tip:: Alternative Logging Configurations
209+
210+
To see examples of other ways to configure the logger,
211+
visit the ``env_logger`` :github:`GitHub repository <rust-cli/env_logger/tree/main/examples>`.
212+
213+
If you run your application and log against connections at the ``debug``
214+
level, the driver emits messages whenever you open, use, and close a
215+
connection. The following code shows the command for this logging
216+
specification:
217+
218+
.. code-block:: bash
219+
220+
$ RUST_LOG='mongodb::connection=debug' cargo run
221+
222+
With ``debug`` level tracing specified, when you open and use a connection,
223+
the driver generates log messages:
224+
225+
.. io-code-block::
226+
:copyable: false
227+
228+
.. input:: /includes/fundamentals/code-snippets/logging.rs
229+
:language: rust
230+
:dedent:
231+
:start-after: start-operation
232+
:end-before: end-operation
233+
234+
.. output::
235+
:language: console
236+
:visible: false
237+
238+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017
239+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017
240+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017
241+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool ready topologyId="..." serverHost="..." serverPort=27017
242+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection checkout started topologyId="..." serverHost="..." serverPort=27017
243+
[2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection created topologyId="..." serverHost="..." serverPort=27017 driverConnectionId=1
244+
...
245+
246+
.. Additional Information
247+
.. ----------------------
248+
249+
.. TODO For more information about setting client options, see the
250+
.. :ref:`rust-connection-options` guide.
251+
252+
.. TODO .. tip:: Monitoring
253+
..
254+
.. In addition to logging, you can enable server selection and
255+
.. topology monitoring in your application. To learn more, see the
256+
.. :ref:`rust-monitoring` guide.

source/includes/fundamentals-sections.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Fundamentals section:
44
- :ref:`Connect to MongoDB <rust-connection>`
55
- :ref:`Read from and Write to MongoDB <rust-crud>`
66
- :ref:`Perform Aggregations <rust-aggregation>`
7+
- :ref:`Record Driver Events <rust-tracing-logging>`
78
- :ref:`Run A Database Command <rust-run-command>`
89

910
..
@@ -14,7 +15,6 @@ Fundamentals section:
1415
- :ref:`Convert Data to and from BSON <rust-bson>`
1516
- :ref:`Construct Indexes <rust-indexes>`
1617
- :ref:`Specify Collations to Order Results <rust-collations>`
17-
- :ref:`Record Log Messages <rust-logging>`
1818
- :ref:`Monitor Driver Events <rust-monitoring>`
1919
- :ref:`Store and Retrieve Large Files by Using GridFS <rust-gridfs>`
2020
- :ref:`Use a Time Series Collection <rust-time-series>`
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use std::env;
2+
use mongodb::{ bson::doc, error::Result, Client };
3+
4+
#[tokio::main]
5+
async fn main() -> Result<()> {
6+
// begin-logger
7+
env_logger::init();
8+
// end-logger
9+
10+
let uri = "<connection string>";
11+
let client = Client::with_uri_str(uri).await?;
12+
13+
// start-operation
14+
let my_coll = client.database("db").collection("test_coll");
15+
my_coll.insert_one(doc! { "x" : 1 }, None).await?;
16+
// end-operation
17+
18+
Ok(())
19+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use std::env;
2+
use mongodb::{ bson::doc, error::Result, Client };
3+
4+
#[tokio::main]
5+
async fn main() -> Result<()> {
6+
// begin-subscriber
7+
tracing_subscriber::fmt::init();
8+
// end-subscriber
9+
10+
let uri = "<connection string>";
11+
let client = Client::with_uri_str(uri).await?;
12+
13+
// start-operation
14+
let my_coll = client.database("db").collection("test_coll");
15+
my_coll.insert_one(doc! { "x" : 1 }, None).await?;
16+
// end-operation
17+
18+
Ok(())
19+
}

0 commit comments

Comments
 (0)