From fc1c46ffd759834999fec3dbf49e3bcd520dbc86 Mon Sep 17 00:00:00 2001 From: Christian Schwarz Date: Fri, 16 Feb 2018 21:19:15 +0100 Subject: [PATCH] logger: fix ReplaceWith: would case parent field to be nil Now WithField and ReplaceWith are wrappers around a common forkLogger routine regression introduced in 51377a8 --- logger/logger.go | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/logger/logger.go b/logger/logger.go index 57fd5e2..fdfe103 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -92,20 +92,8 @@ func (l *Logger) WithOutlet(outlet Outlet, level Level) *Logger { return child } -func (l *Logger) ReplaceField(field string, val interface{}) *Logger { - l.fields[field] = nil - return l.WithField(field, val) -} - -func (l *Logger) WithField(field string, val interface{}) *Logger { - - l.mtx.Lock() - defer l.mtx.Unlock() - - if val, ok := l.fields[field]; ok && val != nil { - l.logInternalError(nil, - fmt.Sprintf("caller overwrites field '%s'. Stack: %s", field, string(debug.Stack()))) - } +// callers must hold l.mtx +func (l *Logger) forkLogger(field string, val interface{}) *Logger { child := &Logger{ fields: make(Fields, len(l.fields)+1), @@ -119,7 +107,22 @@ func (l *Logger) WithField(field string, val interface{}) *Logger { child.fields[field] = val return child +} +func (l *Logger) ReplaceField(field string, val interface{}) *Logger { + l.mtx.Lock() + defer l.mtx.Unlock() + return l.forkLogger(field, val) +} + +func (l *Logger) WithField(field string, val interface{}) *Logger { + l.mtx.Lock() + defer l.mtx.Unlock() + if val, ok := l.fields[field]; ok && val != nil { + l.logInternalError(nil, + fmt.Sprintf("caller overwrites field '%s'. Stack: %s", field, string(debug.Stack()))) + } + return l.forkLogger(field, val) } func (l *Logger) WithFields(fields Fields) (ret *Logger) {