From 5c6c1c9cb1053307b9a85c9726568cd1a7093d39 Mon Sep 17 00:00:00 2001 From: Joshua Lange Date: Fri, 10 May 2019 19:04:31 -0700 Subject: [PATCH] Remove un-necessary locking (#1) Remove un-necessary locking in the logging API. --- log/log.go | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/log/log.go b/log/log.go index 132411d..f132c48 100644 --- a/log/log.go +++ b/log/log.go @@ -10,6 +10,7 @@ import ( "runtime" "strconv" "sync" + "sync/atomic" "time" "github.com/mattn/go-isatty" @@ -21,7 +22,7 @@ import ( type ( Logger struct { prefix string - level Lvl + level uint32 skip int output io.Writer template *fasttemplate.Template @@ -58,7 +59,7 @@ func init() { func New(prefix string) (l *Logger) { l = &Logger{ - level: INFO, + level: uint32(INFO), skip: 2, prefix: prefix, template: l.newTemplate(defaultHeader), @@ -110,11 +111,11 @@ func (l *Logger) SetPrefix(p string) { } func (l *Logger) Level() Lvl { - return l.level + return Lvl(atomic.LoadUint32(&l.level)) } func (l *Logger) SetLevel(v Lvl) { - l.level = v + atomic.StoreUint32(&l.level, uint32(v)) } func (l *Logger) Output() io.Writer { @@ -348,14 +349,16 @@ func Panicj(j JSON) { } func (l *Logger) log(v Lvl, format string, args ...interface{}) { - l.mutex.Lock() - defer l.mutex.Unlock() - buf := l.bufferPool.Get().(*bytes.Buffer) - buf.Reset() - defer l.bufferPool.Put(buf) - _, file, line, _ := runtime.Caller(l.skip) - - if v >= l.level || v == 0 { + logLevel := l.Level() + + if v >= logLevel || v == 0 { + l.mutex.Lock() + defer l.mutex.Unlock() + buf := l.bufferPool.Get().(*bytes.Buffer) + buf.Reset() + defer l.bufferPool.Put(buf) + _, file, line, _ := runtime.Caller(l.skip) + message := "" if format == "" { message = fmt.Sprint(args...)