forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_test.go
81 lines (72 loc) · 2.51 KB
/
examples_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package kit_test
import (
"time"
"github.com/go-kit/kit/log"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/kit"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"google.golang.org/grpc"
)
var (
customFunc kit.CodeToLevel
)
// Initialization shows a relatively complex initialization sequence.
func Example_initialization() {
// Logger is used, allowing pre-definition of certain fields by the user.
logger := log.NewNopLogger()
// Shared options for the logger, with a custom gRPC code to log level function.
opts := []kit.Option{
kit.WithLevels(customFunc),
}
// Create a server, make sure we put the grpc_ctxtags context before everything else.
_ = grpc.NewServer(
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
kit.UnaryServerInterceptor(logger, opts...),
),
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
kit.StreamServerInterceptor(logger, opts...),
),
)
}
func Example_initializationWithDurationFieldOverride() {
// Logger is used, allowing pre-definition of certain fields by the user.
logger := log.NewNopLogger()
// Shared options for the logger, with a custom duration to log field function.
opts := []kit.Option{
kit.WithDurationField(func(duration time.Duration) []interface{} {
return kit.DurationToTimeMillisField(duration)
}),
}
_ = grpc.NewServer(
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(),
kit.UnaryServerInterceptor(logger, opts...),
),
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(),
kit.StreamServerInterceptor(logger, opts...),
),
)
}
func ExampleWithDecider() {
opts := []kit.Option{
kit.WithDecider(func(methodFullName string, err error) bool {
// will not log gRPC calls if it was a call to healthcheck and no error was raised
if err == nil && methodFullName == "blah.foo.healthcheck" {
return false
}
// by default you will log all calls
return true
}),
}
_ = []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(),
kit.StreamServerInterceptor(log.NewNopLogger(), opts...)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(),
kit.UnaryServerInterceptor(log.NewNopLogger(), opts...)),
}
}