...
1 package grpc_zap_test
2
3 import (
4 "context"
5 "time"
6
7 grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
8 grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
9 "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
10 grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
11 pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
12 "go.uber.org/zap"
13 "go.uber.org/zap/zapcore"
14 "google.golang.org/grpc"
15 )
16
17 var (
18 zapLogger *zap.Logger
19 customFunc grpc_zap.CodeToLevel
20 )
21
22
23 func Example_initialization() {
24
25 opts := []grpc_zap.Option{
26 grpc_zap.WithLevels(customFunc),
27 }
28
29 grpc_zap.ReplaceGrpcLoggerV2(zapLogger)
30
31 _ = grpc.NewServer(
32 grpc_middleware.WithUnaryServerChain(
33 grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
34 grpc_zap.UnaryServerInterceptor(zapLogger, opts...),
35 ),
36 grpc_middleware.WithStreamServerChain(
37 grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
38 grpc_zap.StreamServerInterceptor(zapLogger, opts...),
39 ),
40 )
41 }
42
43
44 func Example_initializationWithDurationFieldOverride() {
45 opts := []grpc_zap.Option{
46 grpc_zap.WithDurationField(func(duration time.Duration) zapcore.Field {
47 return zap.Int64("grpc.time_ns", duration.Nanoseconds())
48 }),
49 }
50
51 _ = grpc.NewServer(
52 grpc_middleware.WithUnaryServerChain(
53 grpc_ctxtags.UnaryServerInterceptor(),
54 grpc_zap.UnaryServerInterceptor(zapLogger, opts...),
55 ),
56 grpc_middleware.WithStreamServerChain(
57 grpc_ctxtags.StreamServerInterceptor(),
58 grpc_zap.StreamServerInterceptor(zapLogger, opts...),
59 ),
60 )
61 }
62
63
64 func ExampleExtract_unary() {
65 _ = func(ctx context.Context, ping *pb_testproto.PingRequest) (*pb_testproto.PingResponse, error) {
66
67 grpc_ctxtags.Extract(ctx).Set("custom_tags.string", "something").Set("custom_tags.int", 1337)
68
69
70 l := ctxzap.Extract(ctx)
71 l.Info("some ping")
72 l.Info("another ping")
73 return &pb_testproto.PingResponse{Value: ping.Value}, nil
74 }
75 }
76
77 func Example_initializationWithDecider() {
78 opts := []grpc_zap.Option{
79 grpc_zap.WithDecider(func(fullMethodName string, err error) bool {
80
81 if err == nil && fullMethodName == "foo.bar.healthcheck" {
82 return false
83 }
84
85
86 return true
87 }),
88 }
89
90 _ = []grpc.ServerOption{
91 grpc_middleware.WithStreamServerChain(
92 grpc_ctxtags.StreamServerInterceptor(),
93 grpc_zap.StreamServerInterceptor(zap.NewNop(), opts...)),
94 grpc_middleware.WithUnaryServerChain(
95 grpc_ctxtags.UnaryServerInterceptor(),
96 grpc_zap.UnaryServerInterceptor(zap.NewNop(), opts...)),
97 }
98 }
99
View as plain text