trace.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "bytes"
  16. "fmt"
  17. "time"
  18. "github.com/golang/glog"
  19. )
  20. type traceStep struct {
  21. stepTime time.Time
  22. msg string
  23. }
  24. type Trace struct {
  25. name string
  26. startTime time.Time
  27. steps []traceStep
  28. }
  29. func NewTrace(name string) *Trace {
  30. return &Trace{name, time.Now(), nil}
  31. }
  32. func (t *Trace) Step(msg string) {
  33. if t.steps == nil {
  34. // traces almost always have less than 6 steps, do this to avoid more than a single allocation
  35. t.steps = make([]traceStep, 0, 6)
  36. }
  37. t.steps = append(t.steps, traceStep{time.Now(), msg})
  38. }
  39. func (t *Trace) Log() {
  40. endTime := time.Now()
  41. var buffer bytes.Buffer
  42. buffer.WriteString(fmt.Sprintf("Trace %q (started %v):\n", t.name, t.startTime))
  43. lastStepTime := t.startTime
  44. for _, step := range t.steps {
  45. buffer.WriteString(fmt.Sprintf("[%v] [%v] %v\n", step.stepTime.Sub(t.startTime), step.stepTime.Sub(lastStepTime), step.msg))
  46. lastStepTime = step.stepTime
  47. }
  48. buffer.WriteString(fmt.Sprintf("[%v] [%v] END\n", endTime.Sub(t.startTime), endTime.Sub(lastStepTime)))
  49. glog.Info(buffer.String())
  50. }
  51. func (t *Trace) LogIfLong(threshold time.Duration) {
  52. if time.Since(t.startTime) >= threshold {
  53. t.Log()
  54. }
  55. }
  56. func (t *Trace) TotalTime() time.Duration {
  57. return time.Since(t.startTime)
  58. }