Add Menu.Log as BufferedLogger

This commit is contained in:
qowevisa 2024-10-19 10:04:17 +03:00
parent 1a4d39fd1d
commit 3adb36e336
2 changed files with 51 additions and 0 deletions

47
simple/logger.go Normal file
View File

@ -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)
}

View File

@ -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 := ""