...

Source file src/go.mongodb.org/mongo-driver/event/examples_test.go

Documentation: go.mongodb.org/mongo-driver/event

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     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  // Event examples
    20  
    21  // CommandMonitor represents a monitor that is triggered for different events.
    22  func ExampleCommandMonitor() {
    23  	// If the application makes multiple concurrent requests, it would have to
    24  	// use a concurrent map like sync.Map
    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  			// Empty "startedCommands" for the request ID to avoid a memory leak.
    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  			// Empty "startedCommands" for the request ID to avoid a memory leak.
    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