hlctl/ctllog/log.go

94 lines
1.9 KiB
Go

package ctllog
import (
"fmt"
"io"
"os"
"runtime/debug"
"strings"
)
var (
logfile io.Writer
)
func init() {
if os.Getenv("debug") == "true" {
path := fmt.Sprintf("%s/.hlctl.log", os.Getenv("HOME"))
file, err := os.Create(path)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not open [%s] for logging: %s\n", path, err)
fmt.Fprintln(os.Stderr, "Defaulting to stderr")
logfile = os.Stderr
}
logfile = file
} else {
logfile = os.Stderr
}
}
type Logger struct {
coloredName string
}
func (Logger) New(name string, color ColorRGB) Logger {
coloredName := getStr("[ "+name+" ]", Foreground, color)
return Logger{
coloredName: coloredName,
}
}
func (l Logger) print(str string) {
lines := strings.Split(str, "\n")
for i, line := range lines {
lines[i] = fmt.Sprintf("%s: %s", l.coloredName, line)
}
str = strings.Join(lines, "\n")
fmt.Fprintln(logfile, str)
}
func (l Logger) colored(color ColorRGB, args ...any) {
l.print(getStr(fmt.Sprint(args...), Foreground, color))
}
func (l Logger) coloredf(color ColorRGB, format string, args ...any) {
l.print(getStr(fmt.Sprintf(format, args...), Foreground, color))
}
func (l Logger) fatal(str string) {
l.print(getStr(str, Background, Red))
debug.PrintStack()
os.Exit(16)
}
func (l Logger) Print(args ...any) {
l.print(fmt.Sprint(args...))
}
func (l Logger) Printf(format string, args ...any) {
l.print(fmt.Sprintf(format, args...))
}
func (l Logger) Warn(args ...any) {
l.colored(Yellow, args...)
}
func (l Logger) Warnf(format string, args ...any) {
l.coloredf(Yellow, format, args...)
}
func (l Logger) Error(args ...any) {
l.colored(Red, args...)
}
func (l Logger) Errorf(format string, args ...any) {
l.coloredf(Red, format, args...)
}
func (l Logger) Fatal(args ...any) {
l.fatal(fmt.Sprint(args...))
}
func (l Logger) Fatalf(format string, args ...any) {
l.fatal(fmt.Sprintf(format, args...))
}