From c333c8bd1cfa9d5fb07c7e9faea8898b44ebb502 Mon Sep 17 00:00:00 2001 From: Chris LaPointe Date: Mon, 29 Jul 2024 20:05:50 -0400 Subject: [PATCH] Fix logger race. Resolves #105 (#107) Fix logger race. Resolves #105 --- pkg/logger/logger.go | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index e0b48318..8f7ae4b9 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -2,14 +2,15 @@ package logger import ( "bytes" - "fmt" "log" "os" + "sync" ) // ErrLog is the logger that is controlled by this log controller var logger *log.Logger var logBuffer *bytes.Buffer +var mux sync.RWMutex const logPrefix = "[Log] " @@ -22,6 +23,9 @@ func init() { // DeferLogs enables the log-buffer and defers any logs from printing to the screen func DeferLogs() { + mux.Lock() + defer mux.Unlock() + if logBuffer == nil { logBuffer = new(bytes.Buffer) logger = log.New(logBuffer, logPrefix, 0) @@ -30,6 +34,9 @@ func DeferLogs() { // ImmediateLogs flushes logs and puts logging back into immediate mode func ImmediateLogs() { + mux.Lock() + defer mux.Unlock() + if logBuffer != nil { os.Stderr.Write(logBuffer.Bytes()) resetLogger() @@ -42,28 +49,46 @@ func resetLogger() { } func Fatalln(code int, s interface{}) { + mux.RLock() + defer mux.RUnlock() + logger.Println(s) OsExit(code) } func Fatal(code int, v ...interface{}) { + mux.RLock() + defer mux.RUnlock() + logger.Print(v...) OsExit(code) } func Fatalf(code int, s string, args ...interface{}) { + mux.RLock() + defer mux.RUnlock() + logger.Printf(s, args...) OsExit(code) } func Println(s interface{}) { + mux.RLock() + defer mux.RUnlock() + logger.Println(s) } func Print(v ...interface{}) { + mux.RLock() + defer mux.RUnlock() + logger.Print(v...) } func Printf(s string, args ...interface{}) { - Println(fmt.Sprintf(s, args...)) + mux.RLock() + defer mux.RUnlock() + + logger.Printf(s, args...) }