diff --git a/tracing/README.md b/tracing/README.md index a2b6a494..c40bc6c4 100644 --- a/tracing/README.md +++ b/tracing/README.md @@ -147,14 +147,7 @@ import ( semconv "go.opentelemetry.io/otel/semconv/v1.10.0" ) -res, err := resource.Merge( - resource.Default(), - resource.NewWithAttributes( - semconv.SchemaURL, - semconv.ServiceNameKey.String("My service"), - semconv.ServiceVersionKey.String("v1.0.0"), - ), -) +res, err := tracing.NewResource("My service", "v1.0.0") ctx, tracer, err := tracing.InitTracing(ctx, "github.com/myrepo/myservice", sdktrace.WithResource(res)) ``` diff --git a/tracing/tracing.go b/tracing/tracing.go index 97303643..85090e72 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -12,7 +12,9 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/jaeger" "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.10.0" "go.opentelemetry.io/otel/trace" ) @@ -80,6 +82,31 @@ func InitTracing(ctx context.Context, libraryName string, opts ...sdktrace.Trace return tracerCtx, tracer, err } +// NewResource creates a resource with sensible defaults. +// Replaces common use case of verbose usage. +func NewResource(serviceName, version string, resources ...*resource.Resource) (*resource.Resource, error) { + res, err := resource.Merge( + resource.Default(), + resource.NewWithAttributes( + semconv.SchemaURL, + semconv.ServiceNameKey.String(serviceName), + semconv.ServiceVersionKey.String(version), + ), + ) + if err != nil { + return nil, errors.Wrap(err, "error in resource.Merge") + } + + for i, res2 := range resources { + res, err = resource.Merge(res, res2) + if err != nil { + return nil, errors.Wrapf(err, "error in resource.Merge on resources index %d", i) + } + } + + return res, nil +} + // NewTracer instantiates a new `Tracer` object with a custom library name. // Must call `InitTracing()` first. // Library name is set in span attribute `otel.library.name`.