-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
74 lines (65 loc) · 1.48 KB
/
grpc.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
package logger
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"time"
)
var DefaultConfigGrpc = ConfigGrpc{
SkipperGrpc: DefaultSkipperGrpc,
}
func GrpcInterceptor(config ConfigGrpc) grpc.UnaryServerInterceptor {
if config.SkipperGrpc == nil {
config.SkipperGrpc = DefaultSkipperGrpc
}
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
log := New(WithFormatter(&JSONFormatter{}))
if config.SkipperGrpc(ctx, info) {
return handler(ctx, req)
}
if config.BeforeFuncGrpc != nil {
config.BeforeFuncGrpc(ctx, info)
}
var (
start = time.Now()
isError bool
)
p, ok := peer.FromContext(ctx)
if ok {
log.WithField(ClientIPField, p.Addr.String())
}
log.WithFields(map[string]interface{}{
StartField: start,
URIField: info.FullMethod,
RequestField: req,
})
defer func() {
var (
code = codes.OK
end = time.Now()
)
if err != nil {
code = status.Code(err)
}
log.WithField(CodeField, code.String())
msg := fmt.Sprintf("latency: %v", end.Sub(start))
if isError {
log.Error(msg)
} else {
log.Info(msg)
}
}()
ctx = context.WithValue(ctx, Key, log)
resp, err = handler(ctx, req)
if err != nil {
isError = true
log.WithField(ErrorsField, err)
} else {
log.WithField(ResponseField, resp)
}
return
}
}