github.com/btwiuse/jiri@v0.0.0-20191125065820-53353bcfef54/log/timetracker.go (about)

     1  // Copyright 2017 The Fuchsia Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package log
     6  
     7  import (
     8  	"fmt"
     9  	"time"
    10  )
    11  
    12  type TimeTracker struct {
    13  	msg       string
    14  	startTime time.Time
    15  	logger    *Logger
    16  	done      bool
    17  }
    18  
    19  func (t *TimeTracker) Done() {
    20  	if t.done {
    21  		return
    22  	}
    23  	duration := time.Since(t.startTime)
    24  	t.done = true
    25  	t.logger.LogTime(t.msg, duration)
    26  }
    27  
    28  func (l *Logger) TrackTime(format string, a ...interface{}) *TimeTracker {
    29  	return &TimeTracker{
    30  		logger:    l,
    31  		startTime: time.Now(),
    32  		msg:       fmt.Sprintf(format, a...),
    33  		done:      false,
    34  	}
    35  }
    36  
    37  func (l *Logger) LogTime(msg string, duration time.Duration) {
    38  	if duration.Nanoseconds() >= l.timeLogThreshold.Nanoseconds() {
    39  		l.Debugf("%.2f seconds taken for operation: %s", duration.Seconds(), msg)
    40  	}
    41  }