vendor/github.com/spf13/jwalterweatherman/log_counter.go
changeset 251 1c52a0eeb952
parent 242 2a9ec03fe5a1
equal deleted inserted replaced
250:c040f992052f 251:1c52a0eeb952
     4 // license that can be found in the LICENSE file.
     4 // license that can be found in the LICENSE file.
     5 
     5 
     6 package jwalterweatherman
     6 package jwalterweatherman
     7 
     7 
     8 import (
     8 import (
       
     9 	"io"
     9 	"sync/atomic"
    10 	"sync/atomic"
    10 )
    11 )
    11 
    12 
    12 type logCounter struct {
    13 // Counter is an io.Writer that increments a counter on Write.
    13 	counter uint64
    14 type Counter struct {
       
    15 	count uint64
    14 }
    16 }
    15 
    17 
    16 func (c *logCounter) incr() {
    18 func (c *Counter) incr() {
    17 	atomic.AddUint64(&c.counter, 1)
    19 	atomic.AddUint64(&c.count, 1)
    18 }
    20 }
    19 
    21 
    20 func (c *logCounter) resetCounter() {
    22 // Reset resets the counter.
    21 	atomic.StoreUint64(&c.counter, 0)
    23 func (c *Counter) Reset() {
       
    24 	atomic.StoreUint64(&c.count, 0)
    22 }
    25 }
    23 
    26 
    24 func (c *logCounter) getCount() uint64 {
    27 // Count returns the current count.
    25 	return atomic.LoadUint64(&c.counter)
    28 func (c *Counter) Count() uint64 {
       
    29 	return atomic.LoadUint64(&c.count)
    26 }
    30 }
    27 
    31 
    28 func (c *logCounter) Write(p []byte) (n int, err error) {
    32 func (c *Counter) Write(p []byte) (n int, err error) {
    29 	c.incr()
    33 	c.incr()
    30 	return len(p), nil
    34 	return len(p), nil
    31 }
    35 }
    32 
    36 
    33 // LogCountForLevel returns the number of log invocations for a given threshold.
    37 // LogCounter creates a LogListener that counts log statements >= the given threshold.
    34 func (n *Notepad) LogCountForLevel(l Threshold) uint64 {
    38 func LogCounter(counter *Counter, t1 Threshold) LogListener {
    35 	return n.logCounters[l].getCount()
    39 	return func(t2 Threshold) io.Writer {
    36 }
    40 		if t2 < t1 {
    37 
    41 			// Not interested in this threshold.
    38 // LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
    42 			return nil
    39 // greater than or equal to a given threshold.
    43 		}
    40 func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
    44 		return counter
    41 	var cnt uint64
       
    42 
       
    43 	for i := int(threshold); i < len(n.logCounters); i++ {
       
    44 		cnt += n.LogCountForLevel(Threshold(i))
       
    45 	}
       
    46 
       
    47 	return cnt
       
    48 }
       
    49 
       
    50 // ResetLogCounters resets the invocation counters for all levels.
       
    51 func (n *Notepad) ResetLogCounters() {
       
    52 	for _, np := range n.logCounters {
       
    53 		np.resetCounter()
       
    54 	}
    45 	}
    55 }
    46 }