Skip to content

Commit 4368a05

Browse files
committed
add grpc logger
1 parent 0f999a5 commit 4368a05

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

internal/xtest/grpclogger.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package xtest
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
8+
"github.com/golang/protobuf/jsonpb"
9+
"github.com/golang/protobuf/proto"
10+
"google.golang.org/grpc"
11+
)
12+
13+
// GrpcLogger use for log raw grpc messages
14+
//
15+
// Usage:
16+
//
17+
// db, err := ydb.Open(context.Background(), connectionString,
18+
// ...
19+
// ydb.With(config.WithGrpcOptions(grpc.WithChainUnaryInterceptor(xtest.NewGrpcLogger(t).UnaryClientInterceptor))),
20+
// )
21+
type GrpcLogger struct {
22+
t testing.TB
23+
}
24+
25+
func NewGrpcLogger(t testing.TB) GrpcLogger {
26+
return GrpcLogger{t: t}
27+
}
28+
29+
func (l GrpcLogger) UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
30+
err := invoker(ctx, method, req, reply, cc, opts...)
31+
l.t.Logf("UnaryClientInterceptor: %s - err: %v\n\nreq:\n%v\n\nresp:\n%v", method, err, protoToString(req), protoToString(reply))
32+
return err
33+
}
34+
35+
func protoToString(v interface{}) string {
36+
if mess, ok := v.(proto.Message); ok {
37+
marshaler := jsonpb.Marshaler{}
38+
res, err := marshaler.MarshalToString(mess)
39+
if err != nil {
40+
return fmt.Sprintf("failed to json marshal of: '%v' with err: ", v, err)
41+
}
42+
return res
43+
}
44+
return fmt.Sprint(v)
45+
}

0 commit comments

Comments
 (0)