Skip to content

Instantly share code, notes, and snippets.

@gebv
Last active November 10, 2022 20:07
Show Gist options
  • Save gebv/6c57be0505d3a9fb68de6143e1ae9495 to your computer and use it in GitHub Desktop.
Save gebv/6c57be0505d3a9fb68de6143e1ae9495 to your computer and use it in GitHub Desktop.
OTEL Example serialize to raw for transport
// You can edit this code!
// Click here and start typing.
package main
import (
"context"
"fmt"
"time"
"go.opentelemetry.io/contrib/propagators/b3"
"go.opentelemetry.io/contrib/propagators/ot"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"go.opentelemetry.io/otel/trace"
)
func main() {
fmt.Println("Hello, 世界")
ctx := context.Background()
shutdownFn := setup()
handle(ctx)
time.Sleep(time.Millisecond * 300)
shutdownFn(ctx)
}
func setup() func(ctx context.Context) error {
exp, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
if err != nil {
panic(err)
}
res := resource.NewSchemaless(
semconv.TelemetrySDKLanguageGo,
semconv.ServiceNameKey.String("example-service"),
)
sampler := tracesdk.AlwaysSample()
tp := tracesdk.NewTracerProvider(
tracesdk.WithSampler(tracesdk.ParentBased(sampler)),
tracesdk.WithBatcher(exp),
tracesdk.WithResource(res),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, // tracecontext
propagation.Baggage{}, // baggage
b3.New(b3.WithInjectEncoding(b3.B3MultipleHeader)), // b3
))
return tp.Shutdown
}
// local handler
func handle(ctx context.Context) {
ctx, span := otel.GetTracerProvider().Tracer("local").Start(ctx, "handle")
time.Sleep(time.Millisecond)
span.End()
// async handler
time.Sleep(time.Millisecond)
network := make(map[string]string)
otel.GetTextMapPropagator().Inject(ctx, propagation.MapCarrier(network))
remoteHandle(network)
}
func remoteHandle(network map[string]string) {
ctx := otel.GetTextMapPropagator().Extract(context.TODO(), propagation.MapCarrier(network))
ctx, span := otel.GetTracerProvider().Tracer("remote").Start(
context.Background(),
"handle",
trace.WithLinks(trace.LinkFromContext(ctx)),
)
time.Sleep(time.Millisecond)
span.End()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment