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