Skip to content

Commit

Permalink
fix: dublication bug in logs
Browse files Browse the repository at this point in the history
  • Loading branch information
zomasec committed Oct 26, 2024
1 parent 9066f3e commit a501d8d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
3 changes: 2 additions & 1 deletion examples/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
func main() {
// Set logging configuration
logify.UseColors = true
logify.MaxLevel = logify.Silent


// Example logging
logify.Infof("This is an %s message", "info")
logify.Infof("This is new info msg")
logify.Warningf("This is a %s message", "warning")
logify.Errorf("This is an %s message", "error")
logify.Debugf("This is a %s message", "debug")
Expand Down
37 changes: 28 additions & 9 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import (
"os"
"strings"
"sync"
"time"
)

var (
UseColors = true
MaxLevel = Info
mutex = &sync.Mutex{}
UseColors = true
MaxLevel = Info
mutex = &sync.Mutex{}
lastLogMessage string
lastLogTime time.Time
duplicationGap = 100 * time.Millisecond // time gap to allow between duplicate logs
)

// log logs the actual message to the screen
Expand All @@ -19,22 +23,37 @@ func log(level Level, label string, format string, args ...interface{}) {
return
}

// Lock immediately to prevent concurrent calls
mutex.Lock()
defer mutex.Unlock()

sb := stringBuilderPool.Get().(*strings.Builder)
defer stringBuilderPool.Put(sb)
defer func() {
sb.Reset()
stringBuilderPool.Put(sb)
}()

// Build the message
getLabel(level, label, sb)

message := fmt.Sprintf(format, args...)
sb.WriteString(message)
if !strings.HasSuffix(message, "\n") {
sb.WriteString("\n")
}

mutex.Lock()
defer mutex.Unlock()
finalMessage := sb.String()

// Deduplicate consecutive identical log entries within a short time window
if finalMessage == lastLogMessage && time.Since(lastLogTime) < duplicationGap {
return
}
lastLogMessage = finalMessage
lastLogTime = time.Now()

// Output to appropriate stream
if level == Silent {
fmt.Fprint(os.Stdout, sb.String())
fmt.Fprint(os.Stdout, finalMessage)
} else {
fmt.Fprint(os.Stderr, sb.String())
fmt.Fprint(os.Stderr, finalMessage)
}
}

0 comments on commit a501d8d

Please sign in to comment.