This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
85 lines (69 loc) · 1.79 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"log"
"net/http"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/stdout"
"go.opentelemetry.io/otel/global"
"go.opentelemetry.io/otel/propagators"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/semconv"
)
var tracer otel.Tracer
func main() {
err := run()
if err != nil {
log.Fatal(err)
}
}
func run() error {
shutdown := initProvider()
defer shutdown()
ctx := context.Background()
tracer = global.Tracer("example")
_, span := tracer.Start(ctx, "main")
defer span.End()
err := request(ctx)
if err != nil {
return err
}
return nil
}
func request(ctx context.Context) error {
_, span := tracer.Start(
ctx,
"get_example",
otel.WithSpanKind(otel.SpanKindClient),
)
defer span.End()
resp, err := http.Get("http://example.com/")
log.Println("GET http://example.com/ -> ", resp.StatusCode)
return err
}
func initProvider() func() {
exp, err := stdout.NewExporter()
handleErr(err, "failed to create exporter")
bsp := sdktrace.NewBatchSpanProcessor(exp)
tracerProvider := sdktrace.NewTracerProvider(
sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),
sdktrace.WithResource(resource.New(
// the service name used to display traces in backends
semconv.ServiceNameKey.String("test-service"),
)),
sdktrace.WithSpanProcessor(bsp),
)
// set global propagator to tracecontext (the default is no-op).
global.SetTextMapPropagator(propagators.TraceContext{})
global.SetTracerProvider(tracerProvider)
return func() {
ctx := context.Background()
handleErr(tracerProvider.Shutdown(ctx), "failed to shutdown provider")
handleErr(exp.Shutdown(ctx), "failed to stop exporter")
}
}
func handleErr(err error, message string) {
if err != nil {
log.Fatalf("%s: %v", message, err)
}
}