/
grpc_logging.go
80 lines (70 loc) · 2.24 KB
/
grpc_logging.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
package middleware
import (
"errors"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
grpcUtils "github.com/weaveworks/common/grpc"
"github.com/weaveworks/common/logging"
"github.com/weaveworks/common/user"
)
const (
gRPC = "gRPC"
errorKey = "err"
)
// An error can implement ShouldLog() to control whether GRPCServerLog will log.
type OptionalLogging interface {
ShouldLog(ctx context.Context, duration time.Duration) bool
}
// GRPCServerLog logs grpc requests, errors, and latency.
type GRPCServerLog struct {
Log logging.Interface
// WithRequest will log the entire request rather than just the error
WithRequest bool
DisableRequestSuccessLog bool
}
// UnaryServerInterceptor returns an interceptor that logs gRPC requests
func (s GRPCServerLog) UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
begin := time.Now()
resp, err := handler(ctx, req)
if err == nil && s.DisableRequestSuccessLog {
return resp, nil
}
var optional OptionalLogging
if errors.As(err, &optional) && !optional.ShouldLog(ctx, time.Since(begin)) {
return resp, err
}
entry := user.LogWith(ctx, s.Log).WithFields(logging.Fields{"method": info.FullMethod, "duration": time.Since(begin)})
if err != nil {
if s.WithRequest {
entry = entry.WithField("request", req)
}
if grpcUtils.IsCanceled(err) {
entry.WithField(errorKey, err).Debugln(gRPC)
} else {
entry.WithField(errorKey, err).Warnln(gRPC)
}
} else {
entry.Debugf("%s (success)", gRPC)
}
return resp, err
}
// StreamServerInterceptor returns an interceptor that logs gRPC requests
func (s GRPCServerLog) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
begin := time.Now()
err := handler(srv, ss)
if err == nil && s.DisableRequestSuccessLog {
return nil
}
entry := user.LogWith(ss.Context(), s.Log).WithFields(logging.Fields{"method": info.FullMethod, "duration": time.Since(begin)})
if err != nil {
if grpcUtils.IsCanceled(err) {
entry.WithField(errorKey, err).Debugln(gRPC)
} else {
entry.WithField(errorKey, err).Warnln(gRPC)
}
} else {
entry.Debugf("%s (success)", gRPC)
}
return err
}