This repository has been archived by the owner on Dec 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelemetry.go
82 lines (72 loc) · 2.28 KB
/
telemetry.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
package telemetry
import (
"os"
"log"
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/credentials"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
)
var (
ServiceName = os.Getenv("SERVICE_NAME")
CollectorURL = os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
Insecure = os.Getenv("INSECURE_MODE")
)
func LogError(c context.Context, err error, message string) {
span := trace.SpanFromContext(c)
span.RecordError(err)
span.SetStatus(codes.Error, message)
}
func GetSpan(ctx context.Context, name string) (context.Context, trace.Span) {
return otel.Tracer(ServiceName).Start(ctx, name)
}
// https://signoz.io/blog/monitoring-your-go-application-with-signoz/#instrumenting-a-sample-golang-app
func Initialize() func(context.Context) error {
if len(ServiceName) == 0 {
panic("SERVICE_NAME not set.")
}
if len(CollectorURL) == 0 {
panic("OTEL_EXPORTER_OTLP_ENDPOINT not set.")
}
if len(Insecure) == 0 {
panic("INSECURE_MODE not set.")
}
secureOption := otlptracegrpc.WithTLSCredentials(credentials.NewClientTLSFromCert(nil, ""))
if len(Insecure) > 0 {
secureOption = otlptracegrpc.WithInsecure()
}
exporter, err := otlptrace.New(
context.Background(),
otlptracegrpc.NewClient(
secureOption,
otlptracegrpc.WithEndpoint(CollectorURL),
),
)
if err != nil {
log.Fatal(err)
}
resources, err := resource.New(
context.Background(),
resource.WithAttributes(
attribute.String("service.name", ServiceName),
attribute.String("library.language", "go"),
),
)
if err != nil {
log.Fatal("Could not set resources: ", err)
}
otel.SetTracerProvider(
sdktrace.NewTracerProvider(
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resources),
),
)
return exporter.Shutdown
}