util.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package mon
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "strings"
  7. "time"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. "github.com/zeromicro/go-zero/core/timex"
  10. )
  11. const mongoAddrSep = ","
  12. var errPlaceholder = errors.New("placeholder")
  13. // FormatAddr formats mongo hosts to a string.
  14. func FormatAddr(hosts []string) string {
  15. return strings.Join(hosts, mongoAddrSep)
  16. }
  17. func logDuration(ctx context.Context, name, method string, startTime time.Duration, err error) {
  18. logDurationWithDoc(ctx, name, method, startTime, err)
  19. }
  20. func logDurationWithDoc(ctx context.Context, name, method string,
  21. startTime time.Duration, err error, docs ...any) {
  22. duration := timex.Since(startTime)
  23. logger := logx.WithContext(ctx).WithDuration(duration)
  24. var content []byte
  25. jerr := errPlaceholder
  26. if len(docs) > 0 {
  27. content, jerr = json.Marshal(docs)
  28. }
  29. if err == nil {
  30. // jerr should not be non-nil, but we don't care much on this,
  31. // if non-nil, we just log without docs.
  32. if jerr != nil {
  33. if logSlowMon.True() && duration > slowThreshold.Load() {
  34. logger.Slowf("mongo(%s) - slowcall - %s - ok", name, method)
  35. } else if logMon.True() {
  36. logger.Infof("mongo(%s) - %s - ok", name, method)
  37. }
  38. } else {
  39. if logSlowMon.True() && duration > slowThreshold.Load() {
  40. logger.Slowf("mongo(%s) - slowcall - %s - ok - %s",
  41. name, method, string(content))
  42. } else if logMon.True() {
  43. logger.Infof("mongo(%s) - %s - ok - %s",
  44. name, method, string(content))
  45. }
  46. }
  47. return
  48. }
  49. if jerr != nil {
  50. logger.Errorf("mongo(%s) - %s - fail(%s)", name, method, err.Error())
  51. } else {
  52. logger.Errorf("mongo(%s) - %s - fail(%s) - %s",
  53. name, method, err.Error(), string(content))
  54. }
  55. }