101 lines
2.2 KiB
Go
101 lines
2.2 KiB
Go
package logger
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
const (
|
|
nc = "\033[0m"
|
|
red = "\033[0;31m"
|
|
yellow = "\033[0;33m"
|
|
gray = "\033[0;30m"
|
|
)
|
|
|
|
const (
|
|
errorPrefix = "Error: "
|
|
fatalPrefix = "Fatal: "
|
|
warningprefix = "Warning: "
|
|
debugprefix = "Debug: "
|
|
)
|
|
|
|
type SimpleLogger struct {
|
|
enableColour bool
|
|
debug bool
|
|
}
|
|
|
|
func (sl *SimpleLogger) printMsg(msg string, dest io.Writer) {
|
|
if msg[len(msg)-1:] != "\n" {
|
|
msg = msg + "\n"
|
|
}
|
|
|
|
n, err := fmt.Fprint(dest, msg)
|
|
if err != nil {
|
|
panic(fmt.Errorf("failed to write message to %v: %w", dest, err))
|
|
}
|
|
if n != len(msg) {
|
|
panic(fmt.Errorf("failed to write the entire message (%d/%d)", n, len(msg)))
|
|
}
|
|
}
|
|
|
|
func (sl *SimpleLogger) colourText(msg string, colour string) string {
|
|
if !sl.enableColour {
|
|
return msg
|
|
}
|
|
return colour + msg + nc
|
|
}
|
|
|
|
func (sl *SimpleLogger) Info(msg string) {
|
|
sl.printMsg(msg, os.Stdout)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Infof(format string, a ...any) {
|
|
sl.printMsg(fmt.Sprintf(format, a...), os.Stdout)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Error(msg string) {
|
|
sl.printMsg(sl.colourText(errorPrefix+msg, red), os.Stderr)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Errorf(format string, a ...any) {
|
|
sl.printMsg(sl.colourText(errorPrefix+fmt.Sprintf(format, a...), red), os.Stderr)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Warning(msg string) {
|
|
sl.printMsg(sl.colourText(warningprefix+msg, yellow), os.Stdout)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Warningf(format string, a ...any) {
|
|
sl.printMsg(sl.colourText(warningprefix+fmt.Sprintf(format, a...), yellow), os.Stdout)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Debug(msg string) {
|
|
if !sl.debug {
|
|
return
|
|
}
|
|
sl.printMsg(sl.colourText(debugprefix+msg, gray), os.Stdout)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Debugf(format string, a ...any) {
|
|
if !sl.debug {
|
|
return
|
|
}
|
|
sl.printMsg(sl.colourText(debugprefix+fmt.Sprintf(format, a...), gray), os.Stdout)
|
|
}
|
|
func (sl *SimpleLogger) Fatal(msg string) {
|
|
sl.printMsg(sl.colourText(fatalPrefix+msg, red), os.Stderr)
|
|
os.Exit(1)
|
|
}
|
|
|
|
func (sl *SimpleLogger) Fatalf(format string, a ...any) {
|
|
sl.printMsg(sl.colourText(fatalPrefix+fmt.Sprintf(format, a...), red), os.Stderr)
|
|
os.Exit(1)
|
|
}
|
|
|
|
func New(colour, debug bool) *SimpleLogger {
|
|
return &SimpleLogger{
|
|
debug: debug,
|
|
enableColour: colour,
|
|
}
|
|
}
|