-
Notifications
You must be signed in to change notification settings - Fork 0
/
otlphttp.go
89 lines (77 loc) · 2.58 KB
/
otlphttp.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
86
87
88
89
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/joy12825/gf.
// Package otlphttp provides gtrace.Tracer implementation using OpenTelemetry protocol.
package otlphttp
import (
"context"
"github.com/joy12825/gf/net/gipv4"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"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.20.0"
)
const (
tracerHostnameTagKey = "hostname"
)
// Init initializes and registers `otlphttp` to global TracerProvider.
//
// The output parameter `Shutdown` is used for waiting exported trace spans to be uploaded,
// which is useful if your program is ending, and you do not want to lose recent spans.
func Init(serviceName, endpoint, path string) (*sdktrace.TracerProvider, error) {
// Try retrieving host ip for tracing info.
var (
intranetIPArray, err = gipv4.GetIntranetIpArray()
hostIP = "NoHostIpFound"
)
if err != nil {
return nil, err
}
if len(intranetIPArray) == 0 {
if intranetIPArray, err = gipv4.GetIpArray(); err != nil {
return nil, err
}
}
if len(intranetIPArray) > 0 {
hostIP = intranetIPArray[0]
}
traceClientHTTP := otlptracehttp.NewClient(
otlptracehttp.WithEndpoint(endpoint),
otlptracehttp.WithURLPath(path),
otlptracehttp.WithInsecure(),
otlptracehttp.WithCompression(1),
)
ctx := context.Background()
traceExp, err := otlptrace.New(ctx, traceClientHTTP)
if err != nil {
return nil, err
}
res, err := resource.New(ctx,
resource.WithFromEnv(),
resource.WithProcess(),
resource.WithTelemetrySDK(),
resource.WithHost(),
resource.WithAttributes(
// The name of the service displayed on the traceback end。
semconv.ServiceNameKey.String(serviceName),
semconv.HostNameKey.String(hostIP),
attribute.String(tracerHostnameTagKey, hostIP),
),
)
bsp := sdktrace.NewBatchSpanProcessor(traceExp)
tracerProvider := sdktrace.NewTracerProvider(
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithResource(res),
sdktrace.WithSpanProcessor(bsp),
)
// Set the global propagator to traceContext (not set by default).
otel.SetTextMapPropagator(propagation.TraceContext{})
otel.SetTracerProvider(tracerProvider)
return tracerProvider, nil
}