| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package otelmongo |
| 5 |
|
| 6 |
import ( |
| 7 |
"go.mongodb.org/mongo-driver/v2/event" |
| 8 |
"go.opentelemetry.io/otel" |
| 9 |
"go.opentelemetry.io/otel/metric" |
| 10 |
"go.opentelemetry.io/otel/trace" |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
const ScopeName = "go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo" |
| 15 |
|
| 16 |
|
| 17 |
type config struct { |
| 18 |
MeterProvider metric.MeterProvider |
| 19 |
TracerProvider trace.TracerProvider |
| 20 |
|
| 21 |
Meter metric.Meter |
| 22 |
Tracer trace.Tracer |
| 23 |
|
| 24 |
CommandAttributeDisabled bool |
| 25 |
|
| 26 |
SpanNameFormatter SpanNameFormatterFunc |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
func newConfig(opts ...Option) config { |
| 31 |
cfg := config{ |
| 32 |
MeterProvider: otel.GetMeterProvider(), |
| 33 |
TracerProvider: otel.GetTracerProvider(), |
| 34 |
CommandAttributeDisabled: true, |
| 35 |
} |
| 36 |
|
| 37 |
cfg.SpanNameFormatter = func(event *event.CommandStartedEvent) string { |
| 38 |
collection, _ := extractCollection(event) |
| 39 |
if collection != "" { |
| 40 |
return collection + "." + event.CommandName |
| 41 |
} |
| 42 |
|
| 43 |
return event.CommandName |
| 44 |
} |
| 45 |
|
| 46 |
for _, opt := range opts { |
| 47 |
opt.apply(&cfg) |
| 48 |
} |
| 49 |
|
| 50 |
cfg.Meter = cfg.MeterProvider.Meter( |
| 51 |
ScopeName, |
| 52 |
metric.WithInstrumentationVersion(Version), |
| 53 |
) |
| 54 |
|
| 55 |
cfg.Tracer = cfg.TracerProvider.Tracer( |
| 56 |
ScopeName, |
| 57 |
trace.WithInstrumentationVersion(Version), |
| 58 |
) |
| 59 |
return cfg |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
type Option interface { |
| 64 |
apply(*config) |
| 65 |
} |
| 66 |
|
| 67 |
type optionFunc func(*config) |
| 68 |
|
| 69 |
func (o optionFunc) apply(c *config) { |
| 70 |
o(c) |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
func WithMeterProvider(provider metric.MeterProvider) Option { |
| 76 |
return optionFunc(func(cfg *config) { |
| 77 |
if provider != nil { |
| 78 |
cfg.MeterProvider = provider |
| 79 |
} |
| 80 |
}) |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
type SpanNameFormatterFunc func(e *event.CommandStartedEvent) string |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
func WithSpanNameFormatter(resolver SpanNameFormatterFunc) Option { |
| 92 |
return optionFunc(func(cfg *config) { |
| 93 |
if resolver != nil { |
| 94 |
cfg.SpanNameFormatter = resolver |
| 95 |
} |
| 96 |
}) |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
func WithTracerProvider(provider trace.TracerProvider) Option { |
| 102 |
return optionFunc(func(cfg *config) { |
| 103 |
if provider != nil { |
| 104 |
cfg.TracerProvider = provider |
| 105 |
} |
| 106 |
}) |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
func WithCommandAttributeDisabled(disabled bool) Option { |
| 113 |
return optionFunc(func(cfg *config) { |
| 114 |
cfg.CommandAttributeDisabled = disabled |
| 115 |
}) |
| 116 |
} |