grpc_client.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2020 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. /**
  4. * @Author: mac
  5. * @Description: grpc opentracing clientInterceptor
  6. * @Date: 2020/3/25 10:07
  7. */
  8. package trace
  9. import (
  10. "context"
  11. "github.com/opentracing/opentracing-go"
  12. "github.com/opentracing/opentracing-go/ext"
  13. "github.com/opentracing/opentracing-go/log"
  14. "google.golang.org/grpc"
  15. "google.golang.org/grpc/metadata"
  16. )
  17. func ClientInterceptor() grpc.UnaryClientInterceptor {
  18. return func(ctx context.Context, method string,
  19. req, reply interface{}, cc *grpc.ClientConn,
  20. invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  21. span, ctx := opentracing.StartSpanFromContext(
  22. ctx,
  23. "GRPC client ",
  24. opentracing.Tag{Key: string(ext.Component), Value: "GRPC"},
  25. ext.SpanKindRPCClient,
  26. )
  27. defer span.Finish()
  28. md, ok := metadata.FromOutgoingContext(ctx)
  29. if !ok {
  30. md = metadata.New(nil)
  31. } else {
  32. md = md.Copy()
  33. }
  34. err := opentracing.GlobalTracer().Inject(span.Context(), opentracing.TextMap, MDReaderWriter{md})
  35. if err != nil {
  36. span.SetTag("error", true)
  37. span.LogFields(log.String("inject-error", err.Error()))
  38. }
  39. newCtx := metadata.NewOutgoingContext(ctx, md)
  40. err = invoker(newCtx, method, req, reply, cc, opts...)
  41. if err != nil {
  42. span.SetTag("error", true)
  43. span.LogFields(
  44. log.Object("req", req),
  45. log.Object("reply", reply),
  46. log.String("call-error", err.Error()))
  47. }
  48. return err
  49. }
  50. }