-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathunary_interceptor.go
66 lines (60 loc) · 1.87 KB
/
unary_interceptor.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
package zerolog
import (
"context"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
)
// UnaryInterceptor is a gRPC Server Option that uses NewUnaryServerInterceptor() to log gRPC Requests.
func UnaryInterceptor() grpc.ServerOption {
return grpc.UnaryInterceptor(NewUnaryServerInterceptor())
}
func UnaryInterceptorWithLogger(log *zerolog.Logger) grpc.ServerOption {
return grpc.UnaryInterceptor(NewUnaryServerInterceptorWithLogger(log))
}
// NewUnaryServerInterceptor that logs gRPC Requests using Zerolog.
// {
// ServiceField: "ExampleService",
// MethodField: "ExampleMethod",
// DurationField: 1.00
//
// IpField: "127.0.0.1",
//
// MetadataField: {},
//
// UserAgentField: "ExampleClientUserAgent",
// ReqField: {}, // JSON representation of Request Protobuf
//
// Err: "An unexpected error occurred",
// CodeField: "Unknown",
// MsgField: "Error message returned from the server",
// DetailsField: [Errors],
//
// RespField: {}, // JSON representation of Response Protobuf
//
// ZerologMessageField: "UnaryMessageDefault",
// }
func NewUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return NewUnaryServerInterceptorWithLogger(&log.Logger)
}
func NewUnaryServerInterceptorWithLogger(log *zerolog.Logger) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
now := time.Now()
resp, err := handler(ctx, req)
if log.Error().Enabled() {
if err != nil {
logger := log.Error()
LogIncomingCall(ctx, logger, info.FullMethod, now, req)
LogStatusError(logger, err)
logger.Msg(UnaryMessageDefault)
} else if log.Info().Enabled() {
logger := log.Info()
LogIncomingCall(ctx, logger, info.FullMethod, now, req)
LogResponse(logger, resp)
logger.Msg(UnaryMessageDefault)
}
}
return resp, err
}
}