...
1
2
3
4
5
6
7 package event_test
8
9 import (
10 "context"
11 "log"
12
13 "go.mongodb.org/mongo-driver/bson"
14 "go.mongodb.org/mongo-driver/event"
15 "go.mongodb.org/mongo-driver/mongo"
16 "go.mongodb.org/mongo-driver/mongo/options"
17 )
18
19
20
21
22 func ExampleCommandMonitor() {
23
24
25 startedCommands := make(map[int64]bson.Raw)
26 cmdMonitor := &event.CommandMonitor{
27 Started: func(_ context.Context, evt *event.CommandStartedEvent) {
28 startedCommands[evt.RequestID] = evt.Command
29 },
30 Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) {
31 log.Printf("Command: %v Reply: %v\n",
32 startedCommands[evt.RequestID],
33 evt.Reply,
34 )
35
36
37 delete(startedCommands, evt.RequestID)
38 },
39 Failed: func(_ context.Context, evt *event.CommandFailedEvent) {
40 log.Printf("Command: %v Failure: %v\n",
41 startedCommands[evt.RequestID],
42 evt.Failure,
43 )
44
45
46 delete(startedCommands, evt.RequestID)
47 },
48 }
49 clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetMonitor(cmdMonitor)
50 client, err := mongo.Connect(context.Background(), clientOpts)
51 if err != nil {
52 log.Fatal(err)
53 }
54 defer func() {
55 if err = client.Disconnect(context.TODO()); err != nil {
56 log.Fatal(err)
57 }
58 }()
59 }
60
View as plain text