Add base structure and logger

This commit is contained in:
Melora Hugues 2023-08-13 16:20:55 +02:00
parent d2ac8cb091
commit 914781cd00
5 changed files with 109 additions and 0 deletions

1
config/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build

5
config/Makefile Normal file
View file

@ -0,0 +1,5 @@
.PHONY: build
build:
mkdir -p build/
go build -o build/

3
config/go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.faercol.me/faercol/http-boot-config/config
go 1.20

86
config/logger/logger.go Normal file
View file

@ -0,0 +1,86 @@
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}
}

14
config/main.go Normal file
View file

@ -0,0 +1,14 @@
package main
import "git.faercol.me/faercol/http-boot-config/config/logger"
func main() {
l := logger.NoColour()
l.Info("test message")
l.Warning("this is a warning")
l.Error("this is an error")
l.Fatal("this is fatal")
l.Info("This should not be displayed")
}