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

102 lines
2.2 KiB
Go
Raw Normal View History

2023-08-13 14:20:55 +00:00
package logger
import (
"fmt"
"io"
"os"
)
const (
2023-08-13 15:59:05 +00:00
nc = "\033[0m"
2023-08-13 14:20:55 +00:00
red = "\033[0;31m"
yellow = "\033[0;33m"
2023-08-13 15:59:05 +00:00
gray = "\033[0;30m"
2023-08-13 14:20:55 +00:00
)
const (
errorPrefix = "Error: "
fatalPrefix = "Fatal: "
warningprefix = "Warning: "
2023-08-13 15:59:05 +00:00
debugprefix = "Debug: "
2023-08-13 14:20:55 +00:00
)
type SimpleLogger struct {
enableColour bool
2023-08-13 15:59:05 +00:00
debug bool
2023-08-13 14:20:55 +00:00
}
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
}
2023-08-13 15:59:05 +00:00
return colour + msg + nc
2023-08-13 14:20:55 +00:00
}
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)
}
2023-08-13 15:59:05 +00:00
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)
}
2023-08-13 14:20:55 +00:00
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)
}
2023-08-13 15:59:05 +00:00
func New(colour, debug bool) *SimpleLogger {
return &SimpleLogger{
debug: debug,
enableColour: colour,
}
2023-08-13 14:20:55 +00:00
}