Skip to content

Commit 39a6a8d

Browse files
authored
Merge pull request #30 from mongodben/DOCSP-29229
(DOCSP-29229): Kotlin Logging page
2 parents bc4ef2d + 201d450 commit 39a6a8d

File tree

8 files changed

+138
-83
lines changed

8 files changed

+138
-83
lines changed

examples/build.gradle.kts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@ dependencies {
2020
implementation("org.slf4j:slf4j-api:1.7.32")
2121
implementation("ch.qos.logback:logback-classic:1.2.6")
2222
implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")
23+
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1")
2324
implementation("io.netty:netty-all:4.1.91.Final")
2425
implementation("io.netty:netty-tcnative-boringssl-static:2.0.53.Final:${osdetector.classifier}")
25-
26-
2726
}
2827

2928
tasks.test {
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
2+
3+
import InsertTest.Companion.client
4+
import com.mongodb.kotlin.client.coroutine.MongoClient
5+
import io.github.cdimascio.dotenv.dotenv
6+
import kotlinx.coroutines.flow.firstOrNull
7+
import kotlinx.coroutines.runBlocking
8+
import org.bson.Document
9+
import org.junit.jupiter.api.AfterAll
10+
import org.junit.jupiter.api.Assertions.*
11+
import org.junit.jupiter.api.TestInstance
12+
// :snippet-start: slf4j-import
13+
import org.slf4j.LoggerFactory
14+
// :snippet-end:
15+
import java.util.*
16+
import kotlin.test.*
17+
18+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
19+
internal class LoggingTest {
20+
21+
companion object {
22+
val dotenv = dotenv()
23+
val CONNECTION_URI_PLACEHOLDER = dotenv["MONGODB_CONNECTION_URI"]
24+
val DB_NAME_PLACEHOLDER = "logging"
25+
val COLLECTION_NAME_PLACEHOLDER = "logging"
26+
27+
@AfterAll
28+
@JvmStatic
29+
private fun afterAll() {
30+
runBlocking {
31+
client.close()
32+
}
33+
}
34+
}
35+
@Test
36+
fun triggerLogging() = runBlocking {
37+
// :snippet-start: trigger-logging
38+
val mongoClient = MongoClient.create(CONNECTION_URI_PLACEHOLDER);
39+
val database = mongoClient.getDatabase(DB_NAME_PLACEHOLDER);
40+
val collection = database.getCollection<Document>(COLLECTION_NAME_PLACEHOLDER);
41+
collection.find().firstOrNull()
42+
// :snippet-end:
43+
assertEquals(null, collection.find().firstOrNull())
44+
45+
// clean up
46+
if(collection.countDocuments() > 0){
47+
collection.drop()
48+
}
49+
}
50+
51+
@Test
52+
fun slf4jTest() {
53+
// :snippet-start: slf4j
54+
val loggerParent = LoggerFactory.getLogger("parent")
55+
val loggerChild = LoggerFactory.getLogger("parent.child")
56+
// :snippet-end:
57+
assertEquals("parent", loggerParent.name)
58+
assertEquals("parent.child", loggerChild.name)
59+
}
60+
61+
}
62+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import org.slf4j.LoggerFactory
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
val loggerParent = LoggerFactory.getLogger("parent")
2+
val loggerChild = LoggerFactory.getLogger("parent.child")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
val mongoClient = MongoClient.create(CONNECTION_URI_PLACEHOLDER);
2+
val database = mongoClient.getDatabase(DB_NAME_PLACEHOLDER);
3+
val collection = database.getCollection<Document>(COLLECTION_NAME_PLACEHOLDER);
4+
collection.find().firstOrNull()

source/fundamentals/logging.txt

Lines changed: 65 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,14 @@ Logging
1717
Overview
1818
--------
1919

20-
.. What is on this page?
21-
2220
In this guide, you can learn how to set up and configure a logger in the
23-
MongoDB Java driver.
24-
25-
.. What do any new terms mean?
26-
27-
.. Not applicable. We are treating definition of logger as understood.
28-
29-
.. What can you expect to see on this page?
21+
MongoDB Kotlin driver.
3022

3123
You will learn how to:
3224

3325
- Set up a logger using the Simple Logging Facade For Java (SLF4J)
3426
- Configure the log level of your logger
3527

36-
.. Who should read this? Where should I go if this isn't the page I was looking for?
37-
3828
This guide shows how to record events in the driver.
3929
If you would like to learn how to use information about the activity of the
4030
driver in code, consider reading our
@@ -49,13 +39,13 @@ logger and provides an example logger setup.
4939
Background
5040
~~~~~~~~~~
5141

52-
The MongoDB Java driver uses the Simple Logging Facade For Java (SLF4J).
42+
The MongoDB Kotlin driver uses the Simple Logging Facade For Java (SLF4J).
5343
SLF4J allows you to specify your logging framework of choice at deployment time.
5444
For more information on SLF4J,
5545
`see the SLF4J documentation <http://www.slf4j.org/>`__.
5646

5747
Setting up a logger is optional. When you start your application the MongoDB
58-
Java driver looks for the ``slf4j-api`` artifact in your classpath. If the driver
48+
Kotlin driver looks for the ``slf4j-api`` artifact in your classpath. If the driver
5949
can't find the ``slf4j-api`` artifact, the driver logs the following warning with
6050
``java.util.logging`` and disables all further logging:
6151

@@ -118,24 +108,25 @@ tab corresponding to the logging framework you would like to use in your project
118108
.. tab:: Gradle
119109
:tabid: gradle
120110

121-
Add the following dependency to your ``build.gradle`` file.
111+
Add the following dependency to your ``build.gradle.kts`` file:
122112

123113
.. include:: /includes/logback-gradle-versioned.rst
124114

125115
Once you have included the preceding dependency, connect to your
126-
MongoDB instance and retrieve a document with the following code.
116+
MongoDB instance and retrieve a document with the following code:
127117

128-
.. include:: /includes/fundamentals/logging.rst
118+
.. io-code-block::
129119

130-
You should see output that resembles the following:
120+
.. input:: /examples/generated/LoggingTest.snippet.trigger-logging.kt
121+
:language: kotlin
131122

132-
.. code-block:: none
133-
:copyable: false
123+
.. output::
124+
:language: console
134125

135-
...
136-
12:14:55.853 [main] DEBUG org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:3}] to <MongoDB hostname>
137-
12:14:55.861 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" started on database <database> using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname>. The request ID is 5. Command: {"find": "<collection>", "filter": {}, "limit": 1, "singleBatch": true, "$db": "<database>", "lsid": {"id": {"$binary": {"base64": "<_id>", "subType": "04"}}}, "$readPreference": {"mode": "primaryPreferred"}}
138-
12:14:55.864 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" succeeded in 4.34 ms using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname. The request ID is 5. Command reply: {"cursor": {"id": 0, "ns": "<database>.<collection>", "firstBatch": []}, "ok": 1.0, "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1673778535, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "<_id>", "subType": "00"}}, "keyId": 0}}, "operationTime": {"$timestamp": {"t": 1673778535, "i": 1}}}
126+
...
127+
12:14:55.853 [main] DEBUG org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:3}] to <MongoDB hostname>
128+
12:14:55.861 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" started on database <database> using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname>. The request ID is 5. Command: {"find": "<collection>", "filter": {}, "limit": 1, "singleBatch": true, "$db": "<database>", "lsid": {"id": {"$binary": {"base64": "<_id>", "subType": "04"}}}, "$readPreference": {"mode": "primaryPreferred"}}
129+
12:14:55.864 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" succeeded in 4.34 ms using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname. The request ID is 5. Command reply: {"cursor": {"id": 0, "ns": "<database>.<collection>", "firstBatch": []}, "ok": 1.0, "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1673778535, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "<_id>", "subType": "00"}}, "keyId": 0}}, "operationTime": {"$timestamp": {"t": 1673778535, "i": 1}}}
139130

140131
.. note:: Default Log Level
141132

@@ -163,34 +154,30 @@ tab corresponding to the logging framework you would like to use in your project
163154
.. tab:: Gradle
164155
:tabid: gradle
165156

166-
Add the following dependency to your ``build.gradle`` file.
157+
Add the following dependency to your ``build.gradle.kts`` file.
167158

168159
.. include:: /includes/log4j2-gradle-versioned.rst
169160

170161
Once you have included the preceding dependency, log an error using the
171-
following code.
162+
following code:
172163

173-
.. code-block:: java
164+
.. literalinclude:: /examples/generated/LoggingTest.snippet.slf4j.kt
165+
:language: kotlin
174166

175-
import org.slf4j.Logger;
176-
import org.slf4j.LoggerFactory;
167+
.. io-code-block::
177168

178-
...
169+
.. input:: /examples/generated/LoggingTest.snippet.slf4j.kt
170+
:language: kotlin
179171

180-
Logger logger = LoggerFactory.getLogger("MyApp");
181-
logger.error("Logging an Error");
172+
.. output::
173+
:language: console
182174

183-
You should see output that resembles the following:
184-
185-
.. code-block:: none
186-
:copyable: false
187-
188-
12:35:00.438 [main] ERROR <my package path> - Logging an Error
175+
12:35:00.438 [main] ERROR <my package path> - Logging an Error
189176

190177
.. note:: Default Log Level
191178

192179
The default log level of Log4J2 is ERROR. This means that running
193-
standard operations in the MongoDB Java driver will not produce output
180+
standard operations in the MongoDB Kotlin driver will not produce output
194181
from Log4J2 without configuration. To learn how to change your Log4J2
195182
logger's log level, see the
196183
:ref:`example in the Configure Your Logger section of this page <configure-log-level>`.
@@ -259,16 +246,17 @@ project.
259246
To test that your logger configuration was successful, run the following
260247
code.
261248

262-
.. include:: /includes/fundamentals/logging.rst
249+
.. io-code-block::
263250

264-
You should see output that resembles the following.
251+
.. input:: /examples/generated/LoggingTest.snippet.trigger-logging.kt
252+
:language: kotlin
265253

266-
.. code-block:: none
267-
:copyable: false
254+
.. output::
255+
:language: console
268256

269-
...
270-
1317 [cluster-ClusterId{value='<your cluster id>', description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
271-
1568 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<server value>}] to <your connection uri>
257+
...
258+
1317 [cluster-ClusterId{value='<your cluster id>', description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
259+
1568 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<server value>}] to <your connection uri>
272260

273261
For more information on configuring Logback, see the
274262
`the Logback Manual <https://logback.qos.ch/manual/configuration.html>`__.
@@ -314,16 +302,17 @@ project.
314302
To test that your logger configuration was successful, run the following
315303
code.
316304

317-
.. include:: /includes/fundamentals/logging.rst
305+
.. io-code-block::
318306

319-
You should see output that resembles the following.
307+
.. input:: /examples/generated/LoggingTest.snippet.trigger-logging.kt
308+
:language: kotlin
320309

321-
.. code-block:: none
322-
:copyable: false
310+
.. output::
311+
:language: console
323312

324-
...
325-
10:14:57.633 [cluster-ClusterId{value=<your cluster id>, description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
326-
10:14:57.790 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
313+
...
314+
10:14:57.633 [cluster-ClusterId{value=<your cluster id>, description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
315+
10:14:57.790 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
327316

328317
For more information on configuring Log4j2, see the official
329318
`Log4j2 configuration guide
@@ -340,22 +329,18 @@ ancestor of ``"grandparent.parent.child"``.
340329

341330
For a concrete example, this is what a logger hierarchy looks like in code.
342331

343-
.. code-block:: java
344-
345-
import org.slf4j.Logger;
346-
import org.slf4j.LoggerFactory;
332+
.. literalinclude:: /examples/generated/LoggingTest.snippet.slf4j-import.kt
333+
:language: kotlin
347334

348-
...
349-
350-
Logger logger_parent = LoggerFactory.getLogger("parent");
351-
Logger logger_child = LoggerFactory.getLogger("parent.child");
335+
.. literalinclude:: /examples/generated/LoggingTest.snippet.slf4j.kt
336+
:language: kotlin
352337

353338
A logger inherits the properties of its ancestor logger and can define
354-
its own. You can think of this as similar to class inheritance in Java.
339+
its own. You can think of this as similar to class inheritance in Kotlin.
355340

356-
The MongoDB Java driver defines the following logger names to organize different
341+
The MongoDB Kotlin driver defines the following logger names to organize different
357342
logging events in the driver. Here are the logger names defined in the driver
358-
and the logging events they correspond to.
343+
and the logging events they correspond to:
359344

360345
* ``org.mongodb.driver.authenticator`` : authentication
361346
* ``org.mongodb.driver.client`` : events related to ``MongoClient`` instances
@@ -404,18 +389,19 @@ project.
404389
</configuration>
405390

406391
To test that your logger configuration was successful, run the following
407-
code.
392+
code:
408393

409-
.. include:: /includes/fundamentals/logging.rst
394+
.. io-code-block::
410395

411-
You should see output that resembles the following.
396+
.. input:: /examples/generated/LoggingTest.snippet.trigger-logging.kt
397+
:language: kotlin
412398

413-
.. code-block:: none
414-
:copyable: false
399+
.. output::
400+
:language: console
415401

416-
...
417-
829 [cluster-rtt-ClusterId{value='<some value>', description='null'}-<your connection URI>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:2, serverValue:<your server value>}] to <your connection uri>
418-
977 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
402+
...
403+
829 [cluster-rtt-ClusterId{value='<some value>', description='null'}-<your connection URI>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:2, serverValue:<your server value>}] to <your connection uri>
404+
977 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
419405

420406
For more information on configuring Logback, see the
421407
`official Logback configuration guide <https://logback.qos.ch/manual/configuration.html#syntax>`__.
@@ -448,16 +434,17 @@ project.
448434
To test that your logger configuration was successful, run the following
449435
code.
450436

451-
.. include:: /includes/fundamentals/logging.rst
437+
.. io-code-block::
452438

453-
You should see output that resembles the following.
439+
.. input:: /examples/generated/LoggingTest.snippet.trigger-logging.kt
440+
:language: kotlin
454441

455-
.. code-block:: none
456-
:copyable: false
442+
.. output::
443+
:language: console
457444

458-
...
459-
15:40:23.005 [cluster-ClusterId{value='<some value>', description='null'}-<your connection uri>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:<your server value>}] to <your connection uri>
460-
15:40:23.159 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
445+
...
446+
15:40:23.005 [cluster-ClusterId{value='<some value>', description='null'}-<your connection uri>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:<your server value>}] to <your connection uri>
447+
15:40:23.159 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>
461448

462449
For more information on configuring Log4j2, see the
463450
`official Log4J2 configuration guide <https://logging.apache.org/log4j/2.x/manual/configuration.html>`__.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.. code-block:: groovy
22
33
dependencies {
4-
implementation 'org.apache.logging.log4j:log4j-slf4j-impl:{+log4j2Version+}'
4+
implementation("org.apache.logging.log4j:log4j-slf4j-impl:{+log4j2Version+}")
55
}
66
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
.. code-block:: groovy
1+
.. code-block:: kotlin
22
33
dependencies {
4-
implementation 'ch.qos.logback:logback-classic:{+logbackVersion+}'
4+
implementation("ch.qos.logback:logback-classic:{+logbackVersion+}")
55
}
66

0 commit comments

Comments
 (0)