/
grpc_middleware.go
47 lines (39 loc) · 1.57 KB
/
grpc_middleware.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
package grpc
import (
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
// codeTolevel redirects OK to DEBUG level logging instead of info
// this is example how you can log serveral gRPC code results
func codeToLevel(code codes.Code) zapcore.Level {
if code == codes.OK {
// It is DEBUG
return zap.DebugLevel
}
return grpc_zap.DefaultCodeToLevel(code)
}
// AddLogging returns grpc.Server config option that turn on logging.
func AddLogging(logger *zap.Logger, opts []grpc.ServerOption) []grpc.ServerOption {
// shared options for the logger, with a custom gRPC code to log level function
o := []grpc_zap.Option{
grpc_zap.WithLevels(codeToLevel),
}
// Make sure log statements internal to gRPC library are logged using the zapLogger as well
grpc_zap.ReplaceGrpcLogger(logger)
// Add unary interceptor
opts = append(opts, grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.UnaryServerInterceptor(logger, o...),
))
// Add stream interceptor (added as an example here)
opts = append(opts, grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.StreamServerInterceptor(logger, o...),
))
return opts
}