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