...

Source file src/cloud.google.com/go/internal/testutil/trace_otel.go

Documentation: cloud.google.com/go/internal/testutil

     1  // Copyright 2023 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package testutil
    16  
    17  import (
    18  	"context"
    19  
    20  	"go.opentelemetry.io/otel"
    21  	sdktrace "go.opentelemetry.io/otel/sdk/trace"
    22  	"go.opentelemetry.io/otel/sdk/trace/tracetest"
    23  )
    24  
    25  // OpenTelemetryTestExporter is a test utility exporter. It should be created
    26  // with NewOpenTelemetryTestExporter.
    27  type OpenTelemetryTestExporter struct {
    28  	exporter *tracetest.InMemoryExporter
    29  	tp       *sdktrace.TracerProvider
    30  }
    31  
    32  // NewOpenTelemetryTestExporter creates a OpenTelemetryTestExporter with
    33  // underlying InMemoryExporter and TracerProvider from OpenTelemetry.
    34  func NewOpenTelemetryTestExporter() *OpenTelemetryTestExporter {
    35  	exporter := tracetest.NewInMemoryExporter()
    36  	tp := sdktrace.NewTracerProvider(
    37  		sdktrace.WithSyncer(exporter),
    38  		sdktrace.WithSampler(sdktrace.AlwaysSample()),
    39  	)
    40  	otel.SetTracerProvider(tp)
    41  	return &OpenTelemetryTestExporter{
    42  		exporter: exporter,
    43  		tp:       tp,
    44  	}
    45  }
    46  
    47  // Spans returns the current in-memory stored spans.
    48  func (te *OpenTelemetryTestExporter) Spans() tracetest.SpanStubs {
    49  	return te.exporter.GetSpans()
    50  }
    51  
    52  // Unregister shuts down the underlying OpenTelemetry TracerProvider.
    53  func (te *OpenTelemetryTestExporter) Unregister(ctx context.Context) {
    54  	te.tp.Shutdown(ctx)
    55  }
    56  

View as plain text