Skip to content

Commit

Permalink
Merge pull request #44 from quan-xie/grpc_trace
Browse files Browse the repository at this point in the history
add grpc trace
  • Loading branch information
quan-xie authored Sep 14, 2023
2 parents f8d0c4c + 2feda87 commit 52e5216
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ go get -u github.com/quan-xie/tuba
- [x] Traces (支持zipkin、jagger)
- [x] RPC (GRPC With K8s headless)
- [x] Ecode (Customize Error code)
- [x] Reids (go-redis/v9)
- [ ] Auth
- [ ] Cache (memcache,redis)
- [ ] Service Discovery

35 changes: 35 additions & 0 deletions transport/grpc/server.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package grpc

import (
"context"
"fmt"
"net"
"sync"
"time"

"github.com/pkg/errors"
"github.com/quan-xie/tuba/log"
"github.com/quan-xie/tuba/util/xtime"
"go.opencensus.io/trace"
"google.golang.org/grpc"
xgprc "google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
Expand Down Expand Up @@ -125,3 +129,34 @@ func (s *Server) configuration(c *ServerConfig) (err error) {
s.mutex.Unlock()
return
}

// Tracing Interceptor ....
func TracingInterceptor() grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
// Start a new trace span for the gRPC method.
ctx, span := trace.StartSpan(ctx, fmt.Sprintf("gRPC-%s", info.FullMethod))
defer span.End()

// Add gRPC method information to the span attributes.
span.AddAttributes(
trace.StringAttribute("grpc.method", info.FullMethod),
)

// Call the gRPC handler.
resp, err := handler(ctx, req)
if err != nil {
// Set the error status on the span.
span.SetStatus(trace.Status{
Code: trace.StatusCodeInternal,
Message: err.Error(),
})
}

return resp, err
}
}

0 comments on commit 52e5216

Please sign in to comment.