http-boot-config/config/logger/logger.go

86 lines
1.8 KiB
Go

package logger
import (
"fmt"
"io"
"os"
)
const (
NC = "\033[0m"
red = "\033[0;31m"
yellow = "\033[0;33m"
)
const (
errorPrefix = "Error: "
fatalPrefix = "Fatal: "
warningprefix = "Warning: "
)
type SimpleLogger struct {
enableColour 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) 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 WithColour() *SimpleLogger {
return &SimpleLogger{enableColour: true}
}
func NoColour() *SimpleLogger {
return &SimpleLogger{enableColour: false}
}