7
7
"context"
8
8
"encoding/json"
9
9
"fmt"
10
+ semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
10
11
"net"
11
12
"net/http"
12
13
"os"
@@ -310,7 +311,7 @@ func (cs *checkoutService) PlaceOrder(ctx context.Context, req *pb.PlaceOrderReq
310
311
311
312
// send to kafka only if kafka broker address is set
312
313
if cs .kafkaBrokerSvcAddr != "" {
313
- cs .sendToPostProcessor (orderResult )
314
+ cs .sendToPostProcessor (ctx , orderResult )
314
315
}
315
316
316
317
resp := & pb.PlaceOrderResponse {Order : orderResult }
@@ -473,7 +474,7 @@ func (cs *checkoutService) shipOrder(ctx context.Context, address *pb.Address, i
473
474
return resp .GetTrackingId (), nil
474
475
}
475
476
476
- func (cs * checkoutService ) sendToPostProcessor (result * pb.OrderResult ) {
477
+ func (cs * checkoutService ) sendToPostProcessor (ctx context. Context , result * pb.OrderResult ) {
477
478
message , err := proto .Marshal (result )
478
479
if err != nil {
479
480
log .Errorf ("Failed to marshal message to protobuf: %+v" , err )
@@ -485,7 +486,37 @@ func (cs *checkoutService) sendToPostProcessor(result *pb.OrderResult) {
485
486
Value : sarama .ByteEncoder (message ),
486
487
}
487
488
489
+ // Inject tracing info into message
490
+ span := createProducerSpan (ctx , & msg )
491
+ defer span .End ()
492
+
488
493
cs .KafkaProducerClient .Input () <- & msg
489
494
successMsg := <- cs .KafkaProducerClient .Successes ()
490
495
log .Infof ("Successful to write message. offset: %v" , successMsg .Offset )
491
496
}
497
+
498
+ func createProducerSpan (ctx context.Context , msg * sarama.ProducerMessage ) trace.Span {
499
+ spanContext , span := tracer .Start (
500
+ ctx ,
501
+ fmt .Sprintf ("%s publish" , msg .Topic ),
502
+ trace .WithSpanKind (trace .SpanKindProducer ),
503
+ trace .WithAttributes (
504
+ semconv .PeerService ("kafka" ),
505
+ semconv .NetworkTransportTCP ,
506
+ semconv .MessagingSystemKafka ,
507
+ semconv .MessagingDestinationName (msg .Topic ),
508
+ semconv .MessagingOperationPublish ,
509
+ semconv .MessagingKafkaDestinationPartition (int (msg .Partition )),
510
+ ),
511
+ )
512
+
513
+ carrier := propagation.MapCarrier {}
514
+ propagator := otel .GetTextMapPropagator ()
515
+ propagator .Inject (spanContext , carrier )
516
+
517
+ for key , value := range carrier {
518
+ msg .Headers = append (msg .Headers , sarama.RecordHeader {Key : []byte (key ), Value : []byte (value )})
519
+ }
520
+
521
+ return span
522
+ }
0 commit comments