2022-02-09 02:49:29 +08:00
|
|
|
package jaeger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
2022-11-01 20:12:21 +08:00
|
|
|
"github.com/gogf/gf/v2/errors/gcode"
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
|
|
"github.com/gogf/gf/v2/net/gipv4"
|
|
|
|
"github.com/gogf/gf/v2/text/gregex"
|
2022-02-09 02:49:29 +08:00
|
|
|
"go.opentelemetry.io/otel"
|
2022-05-03 22:53:02 +08:00
|
|
|
"go.opentelemetry.io/otel/attribute"
|
2022-02-09 02:49:29 +08:00
|
|
|
"go.opentelemetry.io/otel/exporters/jaeger"
|
|
|
|
"go.opentelemetry.io/otel/sdk/resource"
|
|
|
|
"go.opentelemetry.io/otel/sdk/trace"
|
2022-05-03 22:53:02 +08:00
|
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
tracerHostnameTagKey = "hostname"
|
2022-02-09 02:49:29 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Init initializes and registers jaeger to global TracerProvider.
|
|
|
|
//
|
|
|
|
// The output parameter `flush` 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 string) (*trace.TracerProvider, error) {
|
|
|
|
// Create the Jaeger exporter
|
|
|
|
var endpointOption jaeger.EndpointOption
|
|
|
|
if strings.HasPrefix(endpoint, "http") {
|
|
|
|
// HTTP.
|
|
|
|
endpointOption = jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(endpoint))
|
|
|
|
} else {
|
|
|
|
// UDP.
|
|
|
|
match, err := gregex.MatchString(`(.+):(\d+)`, endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if len(match) < 3 {
|
|
|
|
return nil, gerror.NewCodef(
|
|
|
|
gcode.CodeInvalidParameter, `invalid endpoint "%s"`, endpoint,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
host = match[1]
|
|
|
|
port = match[2]
|
|
|
|
)
|
|
|
|
endpointOption = jaeger.WithAgentEndpoint(
|
|
|
|
jaeger.WithAgentHost(host), jaeger.WithAgentPort(port),
|
|
|
|
)
|
|
|
|
}
|
2022-05-03 22:53:02 +08:00
|
|
|
hostIP, err := gipv4.GetIntranetIp()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-02-09 02:49:29 +08:00
|
|
|
exp, err := jaeger.New(endpointOption)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
tp := trace.NewTracerProvider(
|
|
|
|
// Always be sure to batch in production.
|
|
|
|
trace.WithBatcher(exp),
|
|
|
|
// Record information about this application in a Resource.
|
|
|
|
trace.WithResource(resource.NewWithAttributes(
|
|
|
|
semconv.SchemaURL,
|
|
|
|
semconv.ServiceNameKey.String(serviceName),
|
2022-05-03 22:53:02 +08:00
|
|
|
semconv.HostNameKey.String(hostIP),
|
|
|
|
attribute.String(tracerHostnameTagKey, hostIP),
|
2022-02-09 02:49:29 +08:00
|
|
|
)),
|
|
|
|
)
|
2022-05-03 22:53:02 +08:00
|
|
|
// Register our TracerProvider as the global, so any imported
|
2022-02-09 02:49:29 +08:00
|
|
|
// instrumentation in the future will default to using it.
|
|
|
|
otel.SetTracerProvider(tp)
|
|
|
|
return tp, nil
|
|
|
|
}
|