-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathgrpc.go
More file actions
277 lines (243 loc) · 7.66 KB
/
grpc.go
File metadata and controls
277 lines (243 loc) · 7.66 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package log
import (
"context"
"crypto/rand"
"encoding/base64"
"io"
"path"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type (
// GRPCLogOption is a function that applies a configuration option
// to a GRPC interceptor logger.
GRPCLogOption func(*grpcOptions)
// GRPCClientLogOption is a function that applies a configuration option
// to a GRPC client interceptor logger.
// Deprecated: Use GRPCLogOption instead.
GRPCClientLogOption = GRPCLogOption
grpcOptions struct {
iserr func(codes.Code) bool
disableCallLogging bool
disableCallID bool
logFunc func(ctx context.Context, keyvals ...Fielder)
}
)
// Be nice to tests
var shortID = randShortID
// UnaryServerInterceptor returns a unary interceptor that performs two tasks:
// 1. Enriches the request context with the logger specified in logCtx.
// 2. Logs details of the unary call, unless the WithDisableCallLogging option is provided.
// UnaryServerInterceptor panics if logCtx was not created with Context.
func UnaryServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.UnaryServerInterceptor {
MustContainLogger(logCtx)
o := defaultGRPCOptions()
for _, opt := range opts {
opt(o)
}
logFunc := Print
if o.logFunc != nil {
logFunc = o.logFunc
}
return func(
ctx context.Context,
req any,
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (any, error) {
ctx = WithContext(ctx, logCtx)
if !o.disableCallID {
ctx = With(ctx, KV{RequestIDKey, shortID()})
}
if o.disableCallLogging {
return handler(ctx, req)
}
then := time.Now()
svcKV := KV{K: GRPCServiceKey, V: path.Dir(info.FullMethod)[1:]}
methKV := KV{K: GRPCMethodKey, V: path.Base(info.FullMethod)}
logFunc(ctx, KV{MessageKey, "start"}, svcKV, methKV)
res, err := handler(ctx, req)
stat, _ := status.FromError(err)
ms := timeSince(then).Milliseconds()
codeKV := KV{K: GRPCCodeKey, V: stat.Code()}
durKV := KV{K: GRPCDurationKey, V: ms}
if o.iserr(stat.Code()) {
statKV := KV{K: GRPCStatusKey, V: stat.Message()}
Error(ctx, err, svcKV, methKV, statKV, codeKV, durKV)
return res, err
}
logFunc(ctx, KV{MessageKey, "end"}, svcKV, methKV, codeKV, durKV)
return res, err
}
}
// StreamServerInterceptor returns a stream interceptor that performs two tasks:
// 1. Enriches the request context with the logger specified in logCtx.
// 2. Logs details of the stream call, unless the WithDisableCallLogging option is provided.
// StreamServerInterceptor panics if logCtx was not created with Context.
func StreamServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.StreamServerInterceptor {
MustContainLogger(logCtx)
o := defaultGRPCOptions()
for _, opt := range opts {
opt(o)
}
logFunc := Print
if o.logFunc != nil {
logFunc = o.logFunc
}
return func(
srv any,
stream grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler,
) error {
ctx := WithContext(stream.Context(), logCtx)
if !o.disableCallID {
ctx = With(ctx, KV{RequestIDKey, shortID()})
}
stream = &streamWithContext{stream, ctx}
if o.disableCallLogging {
return handler(srv, stream)
}
then := time.Now()
svcKV := KV{K: GRPCServiceKey, V: path.Dir(info.FullMethod)[1:]}
methKV := KV{K: GRPCMethodKey, V: path.Base(info.FullMethod)}
logFunc(ctx, KV{MessageKey, "start"}, svcKV, methKV)
err := handler(srv, stream)
stat, _ := status.FromError(err)
ms := timeSince(then).Milliseconds()
codeKV := KV{K: GRPCCodeKey, V: stat.Code()}
durKV := KV{K: GRPCDurationKey, V: ms}
if o.iserr(stat.Code()) {
statKV := KV{K: GRPCStatusKey, V: stat.Message()}
Error(ctx, err, svcKV, methKV, statKV, codeKV, durKV)
return err
}
logFunc(ctx, KV{MessageKey, "end"}, svcKV, methKV, codeKV, durKV)
return err
}
}
// UnaryClientInterceptor returns a unary interceptor that logs the request with
// the logger contained in the request context if any.
func UnaryClientInterceptor(opts ...GRPCLogOption) grpc.UnaryClientInterceptor {
o := defaultGRPCOptions()
for _, opt := range opts {
opt(o)
}
logFunc := Print
if o.logFunc != nil {
logFunc = o.logFunc
}
return func(
ctx context.Context,
fullmethod string,
req, reply any,
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
then := time.Now()
svcKV := KV{K: GRPCServiceKey, V: path.Dir(fullmethod)[1:]}
methKV := KV{K: GRPCMethodKey, V: path.Base(fullmethod)}
logFunc(ctx, KV{K: MessageKey, V: "start"}, svcKV, methKV)
err := invoker(ctx, fullmethod, req, reply, cc, opts...)
stat, _ := status.FromError(err)
ms := timeSince(then).Milliseconds()
codeKV := KV{K: GRPCCodeKey, V: stat.Code()}
durKV := KV{K: GRPCDurationKey, V: ms}
if o.iserr(stat.Code()) {
statKV := KV{K: GRPCStatusKey, V: stat.Message()}
Error(ctx, err, svcKV, methKV, statKV, codeKV, durKV)
return err
}
logFunc(ctx, KV{K: MessageKey, V: "end"}, svcKV, methKV, codeKV, durKV)
return err
}
}
// StreamClientInterceptor returns a stream interceptor that logs the request
// with the logger contained in the request context if any.
func StreamClientInterceptor(opts ...GRPCLogOption) grpc.StreamClientInterceptor {
o := defaultGRPCOptions()
for _, opt := range opts {
opt(o)
}
logFunc := Print
if o.logFunc != nil {
logFunc = o.logFunc
}
return func(
ctx context.Context,
desc *grpc.StreamDesc,
cc *grpc.ClientConn,
fullmethod string,
streamer grpc.Streamer,
opts ...grpc.CallOption,
) (grpc.ClientStream, error) {
then := time.Now()
svcKV := KV{K: GRPCServiceKey, V: path.Dir(fullmethod)[1:]}
methKV := KV{K: GRPCMethodKey, V: path.Base(fullmethod)}
logFunc(ctx, KV{K: MessageKey, V: "start"}, svcKV, methKV)
stream, err := streamer(ctx, desc, cc, fullmethod, opts...)
stat, _ := status.FromError(err)
ms := timeSince(then).Milliseconds()
codeKV := KV{K: GRPCCodeKey, V: stat.Code()}
durKV := KV{K: GRPCDurationKey, V: ms}
if o.iserr(stat.Code()) {
statKV := KV{K: GRPCStatusKey, V: stat.Message()}
Error(ctx, err, svcKV, methKV, statKV, codeKV, durKV)
return stream, err
}
logFunc(ctx, KV{K: MessageKey, V: "end"}, svcKV, methKV, codeKV, durKV)
return stream, err
}
}
// WithErrorFunc returns a GRPC logger option that configures the logger to
// consider the given function to determine if a GRPC status code is an error.
func WithErrorFunc(iserr func(codes.Code) bool) GRPCLogOption {
return func(o *grpcOptions) {
o.iserr = iserr
}
}
// WithDisableCallLogging returns a GRPC logger option that disables call
// logging.
func WithDisableCallLogging() GRPCLogOption {
return func(o *grpcOptions) {
o.disableCallLogging = true
}
}
// WithDisableCallID returns a GRPC logger option that disables the
// generation of request IDs.
func WithDisableCallID() GRPCLogOption {
return func(o *grpcOptions) {
o.disableCallID = true
}
}
// WithCallLogFunc returns a GRPC logger option that configures the logger to use
// the given log function instead of log.Print() as default.
func WithCallLogFunc(logFunc func(ctx context.Context, keyvals ...Fielder)) GRPCLogOption {
return func(o *grpcOptions) {
o.logFunc = logFunc
}
}
func defaultGRPCOptions() *grpcOptions {
return &grpcOptions{
iserr: func(c codes.Code) bool {
return c != codes.OK
},
}
}
type streamWithContext struct {
grpc.ServerStream
ctx context.Context
}
func (s *streamWithContext) Context() context.Context {
return s.ctx
}
// randShortID produces a "unique" 6 bytes long string.
// This algorithm favors simplicity and efficiency over true uniqueness.
func randShortID() string {
b := make([]byte, 6)
io.ReadFull(rand.Reader, b) // nolint: errcheck
return base64.RawURLEncoding.EncodeToString(b)
}