Skip to content

Commit

Permalink
Fix logger race. Resolves #105 (#107)
Browse files Browse the repository at this point in the history
Fix logger race. Resolves #105
  • Loading branch information
zix99 authored Jul 30, 2024
1 parent 9b456df commit c333c8b
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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] "

Expand All @@ -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)
Expand All @@ -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()
Expand All @@ -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...)
}

0 comments on commit c333c8b

Please sign in to comment.