1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-11-25 22:41:46 +02:00
Files
opentelemetry-go/exporters/stdout/stdouttrace/example_test.go
Leo Xie 8d3ae4c5ed fix: Fix stdouttrace/example_test to make the trace_id same. (#4855)
* fix: Fix stdouttrace/example_test to make the trace_id same.

* fix: restore Example

---------

Co-authored-by: Damien Mathieu <damien.mathieu@elastic.co>
2024-01-30 09:19:23 -08:00

99 lines
2.5 KiB
Go

// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stdouttrace_test
import (
"context"
"fmt"
"log"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"go.opentelemetry.io/otel/trace"
)
const (
instrumentationName = "github.com/instrumentron"
instrumentationVersion = "0.1.0"
)
var tracer = otel.GetTracerProvider().Tracer(
instrumentationName,
trace.WithInstrumentationVersion(instrumentationVersion),
trace.WithSchemaURL(semconv.SchemaURL),
)
func add(ctx context.Context, x, y int64) (context.Context, int64) {
var span trace.Span
ctx, span = tracer.Start(ctx, "Addition")
defer span.End()
return ctx, x + y
}
func multiply(ctx context.Context, x, y int64) (context.Context, int64) {
var span trace.Span
ctx, span = tracer.Start(ctx, "Multiplication")
defer span.End()
return ctx, x * y
}
func Resource() *resource.Resource {
return resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName("stdout-example"),
semconv.ServiceVersion("0.0.1"),
)
}
func InstallExportPipeline() (func(context.Context) error, error) {
exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
if err != nil {
return nil, fmt.Errorf("creating stdout exporter: %w", err)
}
tracerProvider := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(Resource()),
)
otel.SetTracerProvider(tracerProvider)
return tracerProvider.Shutdown, nil
}
func Example() {
ctx := context.Background()
// Registers a tracer Provider globally.
shutdown, err := InstallExportPipeline()
if err != nil {
log.Fatal(err)
}
defer func() {
if err := shutdown(ctx); err != nil {
log.Fatal(err)
}
}()
ctx, ans := multiply(ctx, 2, 2)
ctx, ans = multiply(ctx, ans, 10)
ctx, ans = add(ctx, ans, 2)
log.Println("the answer is", ans)
}