From 3adb36e336345ebe132abde4ed0a646f083789f3 Mon Sep 17 00:00:00 2001 From: qowevisa Date: Sat, 19 Oct 2024 10:04:17 +0300 Subject: [PATCH] Add Menu.Log as BufferedLogger --- simple/logger.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ simple/menu.go | 4 ++++ 2 files changed, 51 insertions(+) create mode 100644 simple/logger.go diff --git a/simple/logger.go b/simple/logger.go new file mode 100644 index 0000000..53ea20b --- /dev/null +++ b/simple/logger.go @@ -0,0 +1,47 @@ +package simple + +import ( + "bytes" + "fmt" + "log" + "strings" + "sync" + "time" +) + +// BufferedLogger structure buffer log messages +type BufferedLogger struct { + mu sync.Mutex + buffer bytes.Buffer +} + +// Logf buffers the log message with a formatted string +// To print it instantly call Flush +func (bl *BufferedLogger) Logf(format string, args ...interface{}) { + bl.mu.Lock() + defer bl.mu.Unlock() + + // Create log entry with a timestamp + timestamp := time.Now().Format(time.RFC3339) + entry := fmt.Sprintf("[%s] %s", timestamp, fmt.Sprintf(format, args...)) + + if !(strings.Contains(entry, "\n") && entry[len(entry)-1] == '\n') { + entry += "\n" + } + bl.buffer.WriteString(entry) +} + +// Flush outputs all buffered log messages +func (bl *BufferedLogger) Flush() { + bl.mu.Lock() + defer bl.mu.Unlock() + + if bl.buffer.Len() > 0 { + fmt.Print(bl.buffer.String()) + bl.buffer.Reset() + } +} + +func (m *Menu) RedirectLogOutputToBufferedLogger() { + log.SetOutput(&m.Log.buffer) +} diff --git a/simple/menu.go b/simple/menu.go index ae24fc0..78d834e 100644 --- a/simple/menu.go +++ b/simple/menu.go @@ -91,6 +91,8 @@ type Menu struct { usingEscapeCodes bool lineCounter uint // + Log *BufferedLogger + // counterForIDs uint cmdTree *commandTree } @@ -106,6 +108,7 @@ func CreateMenu(options ...SimpleMenuOption) *Menu { Title: conf.Title, BackKey: conf.BackKey, usingEscapeCodes: conf.UsingEscapeCodes, + Log: &BufferedLogger{}, lineCounter: 0, counterForIDs: 1, cmdTree: createCommandTree(), @@ -206,6 +209,7 @@ func (m *Menu) handleInput(input string) { } func (m *Menu) iteration() { + m.Log.Flush() fmt.Printf("%s\n", m.Title) m.lineCounter++ path := ""