trace.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package traceutil
  2. import (
  3. "bytes"
  4. "fmt"
  5. "time"
  6. "github.com/coreos/pkg/capnslog"
  7. "go.uber.org/zap"
  8. )
  9. var (
  10. plog = capnslog.NewPackageLogger("go.etcd.io/etcd", "trace")
  11. )
  12. type Trace struct {
  13. operation string
  14. startTime time.Time
  15. steps []step
  16. }
  17. type step struct {
  18. time time.Time
  19. msg string
  20. }
  21. func New(op string) *Trace {
  22. return &Trace{operation: op, startTime: time.Now()}
  23. }
  24. func (t *Trace) Step(msg string) {
  25. t.steps = append(t.steps, step{time: time.Now(), msg: msg})
  26. }
  27. // Dump all steps in the Trace
  28. func (t *Trace) Log(lg *zap.Logger) {
  29. var buf bytes.Buffer
  30. buf.WriteString(fmt.Sprintf("The tracing of %v request:\n", t.operation))
  31. buf.WriteString("Request started at:")
  32. buf.WriteString(t.startTime.Format("2006-01-02 15:04:05"))
  33. buf.WriteString(fmt.Sprintf(".%06d", t.startTime.Nanosecond()/1000))
  34. buf.WriteString("\n")
  35. lastStepTime := t.startTime
  36. for i, step := range t.steps {
  37. buf.WriteString(fmt.Sprintf("Step %d: %v Time cost: %v\n", i, step.msg, step.time.Sub(lastStepTime)))
  38. //fmt.Println(step.msg, " costs: ", step.time.Sub(lastStepTime))
  39. lastStepTime = step.time
  40. }
  41. buf.WriteString("Trace End\n")
  42. s := buf.String()
  43. if lg != nil {
  44. lg.Info(s)
  45. } else {
  46. plog.Info(s)
  47. }
  48. }