feat: OpenTelemetry tracing support#45
Conversation
Exposes two new `WithContext()` functions that can be used to provide trancing context. Also pulls in the otelmongo package.
|
@jensteichert If you'd rather prefer the more standard approach for Go libraries of expecting |
|
@MrMarvin A more common way for adding context while keeping backwards compatibility would be to provide a second set of methods that accept the context and then call them internally from the old API i.e. the func (repo *Collection[T]) Insert(model T) (T, error) {
return repo.InsertContext(defaultContext(), T)
}
func (repo *Collection[T]) InsertContext(ctx context.Context, model T) (T, error) {
if model.GetID() == "" {
model.SetID(model.NewID())
}
if hook, ok := any(model).(BeforeInsertHook); ok {
if err := hook.BeforeInsert(); err != nil {
return model, err
}
}
res, err := repo.collection.InsertOne(ctx, model)
if err != nil && res != nil {
model.SetID(res.InsertedID.(string))
}
return model, err
}This is also the pattern used by standard library packages like Doing it like this also avoid having the same context on a collection for all operations - ofc depends on the exact usage but if the same collection would be used by something like an API, each operation should use the requests context and I am not sure if it would be so desirable to always create a "copy" of the object using the |
Motivation and context
More and more of our services are otel-tracing enabled. Currently colt does not allow to provide context objects to DB queries, nor does it instrument the underlying MongoDB driver.
This PR
go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongoand uses itsotelmongo.NewMonitor().WithContext()functions, that can be used by clients to provide custom context. However, calling those is optional, making this change backwards compatible.mongo-drivertov1.17.6).Example
Output of running

cmd/tracing/example.gointo a local Jaeger collector: