-
Notifications
You must be signed in to change notification settings - Fork 245
/
context.go
64 lines (53 loc) · 1.91 KB
/
context.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
package logging
import (
"context"
"strings"
log "github.com/authzed/spicedb/internal/logging"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// FieldSpec provides a mapping between a metadata context field and a logging field.
type FieldSpec struct {
metadataKey string
tagKey string
}
// ExtractMetadataField creates a specification for converting gRPC metadata fields
// to log tags.
func ExtractMetadataField(metadataKey, tagKey string) FieldSpec {
return FieldSpec{metadataKey, tagKey}
}
type extractMetadata struct {
fields []FieldSpec
}
func (r *extractMetadata) ServerReporter(ctx context.Context, _ interceptors.CallMeta) (interceptors.Reporter, context.Context) {
md, ok := metadata.FromIncomingContext(ctx)
if ok {
fields := logging.Fields{}
logContext := log.With()
for _, field := range r.fields {
value, ok := md[field.metadataKey]
if ok {
joinedValue := strings.Join(value, ",")
fields = append(fields, field.tagKey)
fields = append(fields, joinedValue)
logContext = logContext.Str(field.tagKey, joinedValue)
}
}
ctx = logging.InjectFields(ctx, fields)
loggerForContext := logContext.Logger()
ctx = loggerForContext.WithContext(ctx)
}
return interceptors.NoopReporter{}, ctx
}
// UnaryServerInterceptor creates an interceptor for extracting fields from requests
// and setting them as log tags.
func UnaryServerInterceptor(fields ...FieldSpec) grpc.UnaryServerInterceptor {
return interceptors.UnaryServerInterceptor(&extractMetadata{fields})
}
// StreamServerInterceptor creates an interceptor for extracting fields from requests
// and setting them as log tags.
func StreamServerInterceptor(fields ...FieldSpec) grpc.StreamServerInterceptor {
return interceptors.StreamServerInterceptor(&extractMetadata{fields})
}