Debian Codegraph @

instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo/example_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelmongo_test
5
6 import (
7 "context"
8 "fmt"
9
10 "go.mongodb.org/mongo-driver/v2/bson"
11 "go.mongodb.org/mongo-driver/v2/event"
12 "go.mongodb.org/mongo-driver/v2/mongo"
13 "go.mongodb.org/mongo-driver/v2/mongo/options"
14
15 "go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo"
16 )
17
18 func Example() {
19 // connect to MongoDB
20 opts := options.Client()
21 opts.Monitor = otelmongo.NewMonitor()
22 opts.ApplyURI("mongodb://localhost:27017")
23 client, err := mongo.Connect(opts)
24 if err != nil {
25 panic(err)
26 }
27
28 defer func() {
29 if err := client.Disconnect(context.TODO()); err != nil {
30 panic(err)
31 }
32 }()
33 db := client.Database("example")
34 inventory := db.Collection("inventory")
35
36 _, err = inventory.InsertOne(context.TODO(), bson.D{
37 {Key: "item", Value: "canvas"},
38 {Key: "qty", Value: 100},
39 {Key: "attributes", Value: bson.A{"cotton"}},
40 {Key: "size", Value: bson.D{
41 {Key: "h", Value: 28},
42 {Key: "w", Value: 35.5},
43 {Key: "uom", Value: "cm"},
44 }},
45 })
46 if err != nil {
47 panic(err)
48 }
49 }
50
51 func ExampleWithSpanNameFormatter() {
52 // connect to MongoDB
53 opts := options.Client()
54 opts.Monitor = otelmongo.NewMonitor(
55 otelmongo.WithSpanNameFormatter(func(event *event.CommandStartedEvent) string {
56 // optionally, the collection name can be extracted for more
57 // descriptive span names; see the extractCollection helper function
58 // in the otelmongo package for an example of how to do this.
59 return fmt.Sprintf("my-prefix-%s", event.CommandName)
60 }),
61 )
62 opts.ApplyURI("mongodb://localhost:27017")
63 client, err := mongo.Connect(opts)
64 if err != nil {
65 panic(err)
66 }
67
68 defer func() {
69 if err := client.Disconnect(context.TODO()); err != nil {
70 panic(err)
71 }
72 }()
73 db := client.Database("mystore")
74 inventory := db.Collection("inventory")
75
76 _, err = inventory.InsertOne(context.TODO(), bson.D{
77 {Key: "item", Value: "canvas"},
78 // [..]
79 })
80 if err != nil {
81 panic(err)
82 }
83 }