1
0
Fork 0

Move basic features of stats logger into base structure

This commit is contained in:
Gregory Eremin 2015-10-27 02:11:09 +03:00
parent 98ff2625a4
commit 1cace592e6
2 changed files with 52 additions and 38 deletions

49
stats/base.go Normal file
View File

@ -0,0 +1,49 @@
package stats
import (
"sync"
"time"
"github.com/rcrowley/go-metrics"
)
type base struct {
sync.Mutex
stats map[string]*baseStats
}
type baseStats struct {
time metrics.Histogram
errors metrics.Counter
}
func (b *base) Add(name string, dur time.Duration) {
b.metrics(name).time.Update(int64(dur))
}
func (b *base) Error(name string) {
b.metrics(name).errors.Inc(1)
}
func (b *base) init() {
b.stats = make(map[string]*baseStats)
}
func (b *base) metrics(name string) *baseStats {
if _, ok := b.stats[name]; !ok {
b.Lock()
defer b.Unlock()
// Double checking being protected by mutex
if s, ok := b.stats[name]; ok {
return s
}
b.stats[name] = &baseStats{
time: metrics.NewHistogram(metrics.NewUniformSample(1000)),
errors: metrics.NewCounter(),
}
}
return b.stats[name]
}

View File

@ -4,30 +4,22 @@ import (
"fmt"
"io"
"os"
"sync"
"time"
"github.com/rcrowley/go-metrics"
)
type Logger struct {
sync.Mutex
base
out io.Writer
interval time.Duration
stats map[string]*loggerStats
}
type loggerStats struct {
time metrics.Histogram
errors metrics.Counter
}
func NewLogger(out io.Writer, interval time.Duration) *Logger {
l := &Logger{
out: out,
interval: interval,
stats: make(map[string]*loggerStats),
}
l.init()
go l.printWithInterval()
return l
@ -37,14 +29,6 @@ func NewStdoutLogger(interval time.Duration) *Logger {
return NewLogger(os.Stdout, interval)
}
func (l *Logger) Add(name string, dur time.Duration) {
l.metrics(name).time.Update(int64(dur))
}
func (l *Logger) Error(name string) {
l.metrics(name).errors.Inc(1)
}
func (l *Logger) Print() {
for name, s := range l.stats {
fmt.Fprintf(l.out, "%s statistics:\n"+
@ -78,22 +62,3 @@ func (l *Logger) printWithInterval() {
l.Print()
}
}
func (l *Logger) metrics(name string) *loggerStats {
if _, ok := l.stats[name]; !ok {
l.Lock()
defer l.Unlock()
// Double checking being protected by mutex
if s, ok := l.stats[name]; ok {
return s
}
l.stats[name] = &loggerStats{
time: metrics.NewHistogram(metrics.NewUniformSample(1000)),
errors: metrics.NewCounter(),
}
}
return l.stats[name]
}