Steel/pkg/cmd/console.go

87 lines
1.5 KiB
Go
Raw Normal View History

package cmd
import (
"bufio"
"fmt"
"os"
"strings"
"sync"
2023-12-16 20:52:05 +01:00
"time"
)
2023-12-16 20:52:05 +01:00
type Log struct {
// Level enum of "info", "warning", "error"
Level string
// Message to be logged
Message string
// Time of the log
Time string
// Source of the log
Source string
}
type LoggerQueue struct {
queue chan Log
}
var Logger = &LoggerQueue{
queue: make(chan Log, 100),
}
func (l *LoggerQueue) log(level string, message string, source string) {
l.queue <- Log{
Level: level,
Message: message,
Time: time.Now().Format("2006/01/02 15:04:05"),
Source: source,
}
}
func (l *LoggerQueue) Info(message string) {
l.log("INFO", message, "")
}
func (l *LoggerQueue) Warning(message string) {
l.log("WARNING", message, "")
}
func (l *LoggerQueue) Error(message string) {
l.log("ERROR", message, "")
}
func (l *LoggerQueue) processLogs() {
for logEntry := range l.queue {
// Move cursor up and clear line
fmt.Printf("%s [%s]: %s\n", logEntry.Time, logEntry.Level, logEntry.Message)
}
}
func Start(wg *sync.WaitGroup, stopChan chan struct{}) {
defer wg.Done()
2023-12-16 20:52:05 +01:00
go Logger.processLogs()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
input, err := reader.ReadString('\n')
if err != nil {
2023-12-16 20:52:05 +01:00
Logger.Error(fmt.Sprintf("Error while reading input: %v", err))
continue
}
input = strings.TrimSpace(input)
switch input {
case "stop":
2023-12-16 20:52:05 +01:00
Logger.Info("Received stop command.")
close(stopChan)
return
default:
2023-12-16 20:52:05 +01:00
Logger.Info(fmt.Sprintf("Unknown command: %s", input))
}
}
}