forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interceptors.go
202 lines (179 loc) · 6.87 KB
/
interceptors.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
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
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package logging
import (
"context"
"fmt"
"io"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
"google.golang.org/protobuf/proto"
)
type reporter struct {
interceptors.CallMeta
ctx context.Context
kind string
startCallLogged bool
opts *options
fields Fields
logger Logger
}
func (c *reporter) PostCall(err error, duration time.Duration) {
if !has(c.opts.loggableEvents, FinishCall) {
return
}
if err == io.EOF {
err = nil
}
code := c.opts.codeFunc(err)
fields := c.fields.WithUnique(ExtractFields(c.ctx))
fields = fields.AppendUnique(Fields{"grpc.code", code.String()})
if err != nil {
fields = fields.AppendUnique(Fields{"grpc.error", fmt.Sprintf("%v", err)})
}
c.logger.Log(c.ctx, c.opts.levelFunc(code), "finished call", fields.AppendUnique(c.opts.durationFieldFunc(duration))...)
}
func (c *reporter) PostMsgSend(payload any, err error, duration time.Duration) {
logLvl := c.opts.levelFunc(c.opts.codeFunc(err))
fields := c.fields.WithUnique(ExtractFields(c.ctx))
if err != nil {
fields = fields.AppendUnique(Fields{"grpc.error", fmt.Sprintf("%v", err)})
}
if !c.startCallLogged && has(c.opts.loggableEvents, StartCall) {
c.startCallLogged = true
c.logger.Log(c.ctx, logLvl, "started call", fields.AppendUnique(c.opts.durationFieldFunc(duration))...)
}
if err != nil || !has(c.opts.loggableEvents, PayloadSent) {
return
}
if c.CallMeta.IsClient {
p, ok := payload.(proto.Message)
if !ok {
c.logger.Log(
c.ctx,
LevelError,
"payload is not a google.golang.org/protobuf/proto.Message; programmatic error?",
fields.AppendUnique(Fields{"grpc.request.type", fmt.Sprintf("%T", payload)})...,
)
return
}
fields = fields.AppendUnique(Fields{"grpc.send.duration", duration.String(), "grpc.request.content", p})
c.logger.Log(c.ctx, logLvl, "request sent", fields...)
} else {
p, ok := payload.(proto.Message)
if !ok {
c.logger.Log(
c.ctx,
LevelError,
"payload is not a google.golang.org/protobuf/proto.Message; programmatic error?",
fields.AppendUnique(Fields{"grpc.response.type", fmt.Sprintf("%T", payload)})...,
)
return
}
fields = fields.AppendUnique(Fields{"grpc.send.duration", duration.String(), "grpc.response.content", p})
c.logger.Log(c.ctx, logLvl, "response sent", fields...)
}
}
func (c *reporter) PostMsgReceive(payload any, err error, duration time.Duration) {
logLvl := c.opts.levelFunc(c.opts.codeFunc(err))
fields := c.fields.WithUnique(ExtractFields(c.ctx))
if err != nil {
fields = fields.AppendUnique(Fields{"grpc.error", fmt.Sprintf("%v", err)})
}
if !c.startCallLogged && has(c.opts.loggableEvents, StartCall) {
c.startCallLogged = true
c.logger.Log(c.ctx, logLvl, "started call", fields.AppendUnique(c.opts.durationFieldFunc(duration))...)
}
if err != nil || !has(c.opts.loggableEvents, PayloadReceived) {
return
}
if !c.CallMeta.IsClient {
p, ok := payload.(proto.Message)
if !ok {
c.logger.Log(
c.ctx,
LevelError,
"payload is not a google.golang.org/protobuf/proto.Message; programmatic error?",
fields.AppendUnique(Fields{"grpc.request.type", fmt.Sprintf("%T", payload)})...,
)
return
}
fields = fields.AppendUnique(Fields{"grpc.recv.duration", duration.String(), "grpc.request.content", p})
c.logger.Log(c.ctx, logLvl, "request received", fields...)
} else {
p, ok := payload.(proto.Message)
if !ok {
c.logger.Log(
c.ctx,
LevelError,
"payload is not a google.golang.org/protobuf/proto.Message; programmatic error?",
fields.AppendUnique(Fields{"grpc.response.type", fmt.Sprintf("%T", payload)})...,
)
return
}
fields = fields.AppendUnique(Fields{"grpc.recv.duration", duration.String(), "grpc.response.content", p})
c.logger.Log(c.ctx, logLvl, "response received", fields...)
}
}
func reportable(logger Logger, opts *options) interceptors.CommonReportableFunc {
return func(ctx context.Context, c interceptors.CallMeta) (interceptors.Reporter, context.Context) {
kind := KindServerFieldValue
if c.IsClient {
kind = KindClientFieldValue
}
// Field dups from context override the common fields.
fields := newCommonFields(kind, c).WithUnique(ExtractFields(ctx))
if !c.IsClient {
if peer, ok := peer.FromContext(ctx); ok {
fields = append(fields, "peer.address", peer.Addr.String())
}
}
if opts.fieldsFromCtxCallMetaFn != nil {
// fieldsFromCtxFn dups override the existing fields.
fields = opts.fieldsFromCtxCallMetaFn(ctx, c).AppendUnique(fields)
}
singleUseFields := Fields{"grpc.start_time", time.Now().Format(opts.timestampFormat)}
if d, ok := ctx.Deadline(); ok {
singleUseFields = singleUseFields.AppendUnique(Fields{"grpc.request.deadline", d.Format(opts.timestampFormat)})
}
return &reporter{
CallMeta: c,
ctx: ctx,
startCallLogged: false,
opts: opts,
fields: fields.WithUnique(singleUseFields),
logger: logger,
kind: kind,
}, InjectFields(ctx, fields)
}
}
// UnaryClientInterceptor returns a new unary client interceptor that optionally logs the execution of external gRPC calls.
// Logger will read existing and write new logging.Fields available in current context.
// See `ExtractFields` and `InjectFields` for details.
func UnaryClientInterceptor(logger Logger, opts ...Option) grpc.UnaryClientInterceptor {
o := evaluateClientOpt(opts)
return interceptors.UnaryClientInterceptor(reportable(logger, o))
}
// StreamClientInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls.
// Logger will read existing and write new logging.Fields available in current context.
// See `ExtractFields` and `InjectFields` for details.
func StreamClientInterceptor(logger Logger, opts ...Option) grpc.StreamClientInterceptor {
o := evaluateClientOpt(opts)
return interceptors.StreamClientInterceptor(reportable(logger, o))
}
// UnaryServerInterceptor returns a new unary server interceptors that optionally logs endpoint handling.
// Logger will read existing and write new logging.Fields available in current context.
// See `ExtractFields` and `InjectFields` for details.
func UnaryServerInterceptor(logger Logger, opts ...Option) grpc.UnaryServerInterceptor {
o := evaluateServerOpt(opts)
return interceptors.UnaryServerInterceptor(reportable(logger, o))
}
// StreamServerInterceptor returns a new stream server interceptors that optionally logs endpoint handling.
// Logger will read existing and write new logging.Fields available in current context.
// See `ExtractFields` and `InjectFields` for details..
func StreamServerInterceptor(logger Logger, opts ...Option) grpc.StreamServerInterceptor {
o := evaluateServerOpt(opts)
return interceptors.StreamServerInterceptor(reportable(logger, o))
}