This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 330
/
grpc_log.go
94 lines (80 loc) · 2.31 KB
/
grpc_log.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
package server
import (
"context"
"time"
"github.com/hashicorp/go-hclog"
"google.golang.org/grpc"
)
// logUnaryInterceptor returns a gRPC unary interceptor that inserts a hclog.Logger
// into the request context.
//
// Additionally, logUnaryInterceptor logs request and response metadata. If verbose
// is set to true, the request and response attributes are logged too.
func logUnaryInterceptor(logger hclog.Logger, verbose bool) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
start := time.Now()
// Log the request.
{
var reqLogArgs []interface{}
// Log the request's attributes only if verbose is set to true.
if verbose {
reqLogArgs = append(reqLogArgs, "request", req)
}
logger.Info(info.FullMethod+" request", reqLogArgs...)
}
// Invoke the handler.
ctx = hclog.WithContext(ctx, logger)
resp, err := handler(ctx, req)
// Log the response.
{
respLogArgs := []interface{}{
"error", err,
"duration", time.Since(start).String(),
}
// Log the response's attributes only if verbose is set to true.
if verbose {
respLogArgs = append(respLogArgs, "response", resp)
}
logger.Info(info.FullMethod+" response", respLogArgs...)
}
return resp, err
}
}
// logUnaryInterceptor returns a gRPC unary interceptor that inserts a hclog.Logger
// into the request context.
//
// Additionally, logUnaryInterceptor logs request and response metadata. If verbose
// is set to true, the request and response attributes are logged too.
func logStreamInterceptor(logger hclog.Logger, verbose bool) grpc.StreamServerInterceptor {
return func(
srv interface{},
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler) error {
start := time.Now()
// Log the request.
logger.Info(info.FullMethod + " request")
// Invoke the handler.
err := handler(srv, &logStream{
ServerStream: ss,
context: hclog.WithContext(ss.Context(), logger),
})
// Log the response.
logger.Info(info.FullMethod+" response",
"error", err,
"duration", time.Since(start).String(),
)
return err
}
}
type logStream struct {
grpc.ServerStream
context context.Context
}
func (s *logStream) Context() context.Context {
return s.context
}