github.com/aclisp/heapster@v0.19.2-0.20160613100040-51756f899a96/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(), nil}
    40  }
    41  
    42  func (t *Trace) Step(msg string) {
    43  	if t.steps == nil {
    44  		// traces almost always have less than 6 steps, do this to avoid more than a single allocation
    45  		t.steps = make([]traceStep, 0, 6)
    46  	}
    47  	t.steps = append(t.steps, traceStep{time.Now(), msg})
    48  }
    49  
    50  func (t *Trace) Log() {
    51  	endTime := time.Now()
    52  	var buffer bytes.Buffer
    53  
    54  	buffer.WriteString(fmt.Sprintf("Trace %q (started %v):\n", t.name, t.startTime))
    55  	lastStepTime := t.startTime
    56  	for _, step := range t.steps {
    57  		buffer.WriteString(fmt.Sprintf("[%v] [%v] %v\n", step.stepTime.Sub(t.startTime), step.stepTime.Sub(lastStepTime), step.msg))
    58  		lastStepTime = step.stepTime
    59  	}
    60  	buffer.WriteString(fmt.Sprintf("[%v] [%v] END\n", endTime.Sub(t.startTime), endTime.Sub(lastStepTime)))
    61  	glog.Info(buffer.String())
    62  }
    63  
    64  func (t *Trace) LogIfLong(threshold time.Duration) {
    65  	if time.Since(t.startTime) >= threshold {
    66  		t.Log()
    67  	}
    68  }
    69  
    70  func (t *Trace) TotalTime() time.Duration {
    71  	return time.Since(t.startTime)
    72  }