From 7916133cbcbe1c703d5959a995d923744afe544a Mon Sep 17 00:00:00 2001 From: Vladimir Popov Date: Tue, 27 Apr 2021 11:48:16 +0700 Subject: [PATCH] Fix data race in spanlogger Signed-off-by: Vladimir Popov --- pkg/tools/log/spanlogger/spanlogger.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pkg/tools/log/spanlogger/spanlogger.go b/pkg/tools/log/spanlogger/spanlogger.go index c433807e7..a92746f16 100644 --- a/pkg/tools/log/spanlogger/spanlogger.go +++ b/pkg/tools/log/spanlogger/spanlogger.go @@ -23,6 +23,7 @@ import ( "fmt" "runtime/debug" "strings" + "sync" "github.com/opentracing/opentracing-go" opentracinglog "github.com/opentracing/opentracing-go/log" @@ -40,6 +41,7 @@ const ( type spanLogger struct { span opentracing.Span entries map[interface{}]interface{} + lock sync.RWMutex } func (s *spanLogger) Info(v ...interface{}) { @@ -91,6 +93,9 @@ func (s *spanLogger) Tracef(format string, v ...interface{}) { } func (s *spanLogger) Object(k, v interface{}) { + s.lock.RLock() + defer s.lock.RUnlock() + if s.span != nil { if v != nil { msg := "" @@ -110,6 +115,9 @@ func (s *spanLogger) Object(k, v interface{}) { } func (s *spanLogger) WithField(key, value interface{}) log.Logger { + s.lock.RLock() + defer s.lock.RUnlock() + data := make(map[interface{}]interface{}, len(s.entries)+1) for k, v := range s.entries { data[k] = v @@ -127,6 +135,9 @@ func (s *spanLogger) log(level string, v ...interface{}) { } func (s *spanLogger) logf(level, format string, v ...interface{}) { + s.lock.RLock() + defer s.lock.RUnlock() + if s.span != nil { if v != nil { s.span.LogFields(opentracinglog.String("event", level), opentracinglog.String("message", fmt.Sprintf(format, v...))) @@ -152,6 +163,9 @@ func FromContext(ctx context.Context, operation string) (context.Context, log.Lo // finish - closes spanLogger func (s *spanLogger) finish() { + s.lock.Lock() + defer s.lock.Unlock() + if s.span != nil { s.span.Finish() s.span = nil