Add Menu.Log as BufferedLogger
This commit is contained in:
parent
1a4d39fd1d
commit
3adb36e336
47
simple/logger.go
Normal file
47
simple/logger.go
Normal 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)
|
||||
}
|
|
@ -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 := ""
|
||||
|
|
Loading…
Reference in New Issue
Block a user