headplane/internal/util/logger.go

77 lines
1.4 KiB
Go
Raw Permalink Normal View History

2025-04-08 14:51:28 -04:00
package util
import (
"encoding/json"
"fmt"
2025-04-08 14:51:28 -04:00
"os"
"sync"
)
type LogLevel string
const (
2025-08-20 13:58:19 -04:00
LevelInfo LogLevel = "INFO"
LevelDebug LogLevel = "DEBUG"
LevelError LogLevel = "ERROR"
LevelFatal LogLevel = "FATAL"
)
type LogMessage struct {
Level LogLevel
Time string
Message any
}
2025-04-08 14:51:28 -04:00
type Logger struct {
debugEnabled bool
encoder *json.Encoder
pool *sync.Pool
2025-04-08 14:51:28 -04:00
}
var logger = NewLogger()
2025-04-08 14:51:28 -04:00
func GetLogger() *Logger {
return logger
}
func NewLogger() *Logger {
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
2025-04-08 14:51:28 -04:00
return &Logger{
encoder: enc,
pool: &sync.Pool{
New: func() any {
return &LogMessage{}
},
},
2025-04-08 14:51:28 -04:00
}
}
func (l *Logger) SetDebug(enabled bool) {
if enabled {
l.debugEnabled = true
l.Info("Enabling Debug logging for headplane-agent")
l.Info("Be careful, this will spam a lot of information")
2025-04-08 14:51:28 -04:00
}
}
func (l *Logger) log(level LogLevel, format string, v ...any) {
msg := fmt.Sprintf(format, v...)
2025-08-20 13:58:19 -04:00
fmt.Printf("LOG %s %s\n", level, msg)
if level == LevelFatal {
os.Exit(1)
}
2025-04-08 14:51:28 -04:00
}
func (l *Logger) Debug(format string, v ...any) {
if l.debugEnabled {
l.log(LevelDebug, format, v...)
2025-04-08 14:51:28 -04:00
}
}
func (l *Logger) Info(format string, v ...any) { l.log(LevelInfo, format, v...) }
func (l *Logger) Error(format string, v ...any) { l.log(LevelError, format, v...) }
func (l *Logger) Fatal(format string, v ...any) { l.log(LevelFatal, format, v...) }