// Configure OpenTelemetry under `Init`func Init() *sdktrace.TracerProvider {if ctx == nil {ctx = context.Background()}// Create an exporter and set the basic endpointopts := []otlptracegrpc.Option{otlptracegrpc.WithEndpoint("<endpoint>"),otlptracegrpc.WithInsecure(),}exporter, err := otlptracegrpc.New(ctx, opts...)if err != nil {log.Fatal(err)}// Set the token or configure the environment variable `OTEL_RESOURCE_ATTRIBUTES=token=xxxxxxxxx`r, err := resource.New(ctx, []resource.Option{// Set the token valueresource.WithAttributes(attribute.KeyValue{Key: "token", Value: attribute.StringValue("<Token>"),}),// Set the service nameresource.WithAttributes(attribute.KeyValue{Key: "service.name", Value: attribute.StringValue("audotanggrpcdemo"),}),}...)if err != nil {log.Fatal(err)}// Create a TracerProvidertp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()),sdktrace.WithBatcher(exporter),sdktrace.WithResource(r),)otel.SetTracerProvider(tp)otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))return tp}
// Initialize the tracetp := trace.Init()defer func() {if err := tp.Shutdown(context.Background()); err != nil {log.Printf("Error shutting down tracer provider: %v", err)}}()// Specify the hosthost := os.Getenv("grpc1")lis, err := net.Listen("tcp", host+":7778")if err != nil {log.Fatalf("failed to listen: %v", err)}
s := grpc.NewServer(grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor()),grpc.StreamInterceptor(otelgrpc.StreamServerInterceptor()),)
// Register our service with the gRPC serverapi.RegisterHelloServiceServer(s, &server{})reflection.Register(s)if err := s.Serve(lis); err != nil {log.Fatalf("failed to serve: %v", err)}
// Initialize the tracetp := trace.Init()defer func() {if err := tp.Shutdown(context.Background()); err != nil {log.Printf("Error shutting down tracer provider: %v", err)}}()
// Establish a connection to the server to configure the interceptorconn, err := grpc.DialContext(context.Background(), "localhost:7778", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
c := api.NewHelloServiceClient(conn)for {callSayHelloClientStream(c)time.Sleep(100 * time.Millisecond)}
Was this page helpful?