1
0

durationinterceptor.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "path"
  5. "sync"
  6. "time"
  7. "github.com/wuntsong-org/go-zero-plus/core/lang"
  8. "github.com/wuntsong-org/go-zero-plus/core/logx"
  9. "github.com/wuntsong-org/go-zero-plus/core/syncx"
  10. "github.com/wuntsong-org/go-zero-plus/core/timex"
  11. "google.golang.org/grpc"
  12. )
  13. const defaultSlowThreshold = time.Millisecond * 500
  14. var (
  15. notLoggingContentMethods sync.Map
  16. slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
  17. )
  18. // DurationInterceptor is an interceptor that logs the processing time.
  19. func DurationInterceptor(ctx context.Context, method string, req, reply any,
  20. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  21. serverName := path.Join(cc.Target(), method)
  22. start := timex.Now()
  23. err := invoker(ctx, method, req, reply, cc, opts...)
  24. if err != nil {
  25. logger := logx.WithContext(ctx).WithDuration(timex.Since(start))
  26. _, ok := notLoggingContentMethods.Load(method)
  27. if ok {
  28. logger.Errorf("fail - %s - %s", serverName, err.Error())
  29. } else {
  30. logger.Errorf("fail - %s - %v - %s", serverName, req, err.Error())
  31. }
  32. } else {
  33. elapsed := timex.Since(start)
  34. if elapsed > slowThreshold.Load() {
  35. logger := logx.WithContext(ctx).WithDuration(elapsed)
  36. _, ok := notLoggingContentMethods.Load(method)
  37. if ok {
  38. logger.Slowf("[RPC] ok - slowcall - %s", serverName)
  39. } else {
  40. logger.Slowf("[RPC] ok - slowcall - %s - %v - %v", serverName, req, reply)
  41. }
  42. }
  43. }
  44. return err
  45. }
  46. // DontLogContentForMethod disable logging content for given method.
  47. func DontLogContentForMethod(method string) {
  48. notLoggingContentMethods.Store(method, lang.Placeholder)
  49. }
  50. // SetSlowThreshold sets the slow threshold.
  51. func SetSlowThreshold(threshold time.Duration) {
  52. slowThreshold.Set(threshold)
  53. }