forked from zeromicro/go-zero
/
durationinterceptor.go
61 lines (53 loc) · 1.73 KB
/
durationinterceptor.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 clientinterceptors
import (
"context"
"path"
"sync"
"time"
"github.com/mikokutou1/go-zero-m/core/lang"
"github.com/mikokutou1/go-zero-m/core/logx"
"github.com/mikokutou1/go-zero-m/core/syncx"
"github.com/mikokutou1/go-zero-m/core/timex"
"google.golang.org/grpc"
)
const defaultSlowThreshold = time.Millisecond * 500
var (
notLoggingContentMethods sync.Map
slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
)
// DurationInterceptor is an interceptor that logs the processing time.
func DurationInterceptor(ctx context.Context, method string, req, reply any,
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
serverName := path.Join(cc.Target(), method)
start := timex.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
logger := logx.WithContext(ctx).WithDuration(timex.Since(start))
_, ok := notLoggingContentMethods.Load(method)
if ok {
logger.Errorf("fail - %s - %s", serverName, err.Error())
} else {
logger.Errorf("fail - %s - %v - %s", serverName, req, err.Error())
}
} else {
elapsed := timex.Since(start)
if elapsed > slowThreshold.Load() {
logger := logx.WithContext(ctx).WithDuration(elapsed)
_, ok := notLoggingContentMethods.Load(method)
if ok {
logger.Slowf("[RPC] ok - slowcall - %s", serverName)
} else {
logger.Slowf("[RPC] ok - slowcall - %s - %v - %v", serverName, req, reply)
}
}
}
return err
}
// DontLogContentForMethod disable logging content for given method.
func DontLogContentForMethod(method string) {
notLoggingContentMethods.Store(method, lang.Placeholder)
}
// SetSlowThreshold sets the slow threshold.
func SetSlowThreshold(threshold time.Duration) {
slowThreshold.Set(threshold)
}