hlctl/ctllog/log.go

94 lines
1.9 KiB
Go
Raw Normal View History

2023-01-07 16:56:15 +00:00
package ctllog
import (
"fmt"
2023-01-07 18:12:19 +00:00
"io"
2023-01-07 16:56:15 +00:00
"os"
"runtime/debug"
"strings"
)
2023-01-07 18:12:19 +00:00
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
}
}
2023-01-07 16:56:15 +00:00
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")
2023-01-07 18:12:19 +00:00
fmt.Fprintln(logfile, str)
2023-01-07 16:56:15 +00:00
}
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...))
}