forked from zeromicro/go-zero
/
statinterceptor.go
61 lines (52 loc) · 1.7 KB
/
statinterceptor.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
package serverinterceptors
import (
"context"
"encoding/json"
"time"
"github.com/MockyBang/go-zero/core/logx"
"github.com/MockyBang/go-zero/core/stat"
"github.com/MockyBang/go-zero/core/syncx"
"github.com/MockyBang/go-zero/core/timex"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
)
const defaultSlowThreshold = time.Millisecond * 500
var slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
// SetSlowThreshold sets the slow threshold.
func SetSlowThreshold(threshold time.Duration) {
slowThreshold.Set(threshold)
}
// UnaryStatInterceptor returns a func that uses given metrics to report stats.
func UnaryStatInterceptor(metrics *stat.Metrics) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp interface{}, err error) {
defer handleCrash(func(r interface{}) {
err = toPanicError(r)
})
startTime := timex.Now()
defer func() {
duration := timex.Since(startTime)
metrics.Add(stat.Task{
Duration: duration,
})
logDuration(ctx, info.FullMethod, req, duration)
}()
return handler(ctx, req)
}
}
func logDuration(ctx context.Context, method string, req interface{}, duration time.Duration) {
var addr string
client, ok := peer.FromContext(ctx)
if ok {
addr = client.Addr.String()
}
content, err := json.Marshal(req)
if err != nil {
logx.WithContext(ctx).Errorf("%s - %s", addr, err.Error())
} else if duration > slowThreshold.Load() {
logx.WithContext(ctx).WithDuration(duration).Slowf("[RPC] slowcall - %s - %s - %s",
addr, method, string(content))
} else {
logx.WithContext(ctx).WithDuration(duration).Infof("%s - %s - %s", addr, method, string(content))
}
}