trace.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 trace
  14. import (
  15. "bytes"
  16. "fmt"
  17. "math/rand"
  18. "time"
  19. "k8s.io/klog"
  20. )
  21. // Field is a key value pair that provides additional details about the trace.
  22. type Field struct {
  23. Key string
  24. Value interface{}
  25. }
  26. func (f Field) format() string {
  27. return fmt.Sprintf("%s:%v", f.Key, f.Value)
  28. }
  29. func writeFields(b *bytes.Buffer, l []Field) {
  30. for i, f := range l {
  31. b.WriteString(f.format())
  32. if i < len(l)-1 {
  33. b.WriteString(",")
  34. }
  35. }
  36. }
  37. type traceStep struct {
  38. stepTime time.Time
  39. msg string
  40. fields []Field
  41. }
  42. // Trace keeps track of a set of "steps" and allows us to log a specific
  43. // step if it took longer than its share of the total allowed time
  44. type Trace struct {
  45. name string
  46. fields []Field
  47. startTime time.Time
  48. steps []traceStep
  49. }
  50. // New creates a Trace with the specified name. The name identifies the operation to be traced. The
  51. // Fields add key value pairs to provide additional details about the trace, such as operation inputs.
  52. func New(name string, fields ...Field) *Trace {
  53. return &Trace{name: name, startTime: time.Now(), fields: fields}
  54. }
  55. // Step adds a new step with a specific message. Call this at the end of an execution step to record
  56. // how long it took. The Fields add key value pairs to provide additional details about the trace
  57. // step.
  58. func (t *Trace) Step(msg string, fields ...Field) {
  59. if t.steps == nil {
  60. // traces almost always have less than 6 steps, do this to avoid more than a single allocation
  61. t.steps = make([]traceStep, 0, 6)
  62. }
  63. t.steps = append(t.steps, traceStep{stepTime: time.Now(), msg: msg, fields: fields})
  64. }
  65. // Log is used to dump all the steps in the Trace
  66. func (t *Trace) Log() {
  67. // an explicit logging request should dump all the steps out at the higher level
  68. t.logWithStepThreshold(0)
  69. }
  70. func (t *Trace) logWithStepThreshold(stepThreshold time.Duration) {
  71. var buffer bytes.Buffer
  72. tracenum := rand.Int31()
  73. endTime := time.Now()
  74. totalTime := endTime.Sub(t.startTime)
  75. buffer.WriteString(fmt.Sprintf("Trace[%d]: %q ", tracenum, t.name))
  76. if len(t.fields) > 0 {
  77. writeFields(&buffer, t.fields)
  78. buffer.WriteString(" ")
  79. }
  80. buffer.WriteString(fmt.Sprintf("(started: %v) (total time: %v):\n", t.startTime, totalTime))
  81. lastStepTime := t.startTime
  82. for _, step := range t.steps {
  83. stepDuration := step.stepTime.Sub(lastStepTime)
  84. if stepThreshold == 0 || stepDuration > stepThreshold || klog.V(4) {
  85. buffer.WriteString(fmt.Sprintf("Trace[%d]: [%v] [%v] ", tracenum, step.stepTime.Sub(t.startTime), stepDuration))
  86. buffer.WriteString(step.msg)
  87. if len(step.fields) > 0 {
  88. buffer.WriteString(" ")
  89. writeFields(&buffer, step.fields)
  90. }
  91. buffer.WriteString("\n")
  92. }
  93. lastStepTime = step.stepTime
  94. }
  95. stepDuration := endTime.Sub(lastStepTime)
  96. if stepThreshold == 0 || stepDuration > stepThreshold || klog.V(4) {
  97. buffer.WriteString(fmt.Sprintf("Trace[%d]: [%v] [%v] END\n", tracenum, endTime.Sub(t.startTime), stepDuration))
  98. }
  99. klog.Info(buffer.String())
  100. }
  101. // LogIfLong is used to dump steps that took longer than its share
  102. func (t *Trace) LogIfLong(threshold time.Duration) {
  103. if time.Since(t.startTime) >= threshold {
  104. // if any step took more than it's share of the total allowed time, it deserves a higher log level
  105. stepThreshold := threshold / time.Duration(len(t.steps)+1)
  106. t.logWithStepThreshold(stepThreshold)
  107. }
  108. }
  109. // TotalTime can be used to figure out how long it took since the Trace was created
  110. func (t *Trace) TotalTime() time.Duration {
  111. return time.Since(t.startTime)
  112. }