new config options and error handles new input any

This commit is contained in:
Adrian Zuercher
2025-04-21 12:59:16 +02:00
parent 6f963ae0a4
commit 29f3ee26f9
5 changed files with 77 additions and 18 deletions

19
logging/cgf.go Normal file
View File

@@ -0,0 +1,19 @@
package logging
type Config struct {
MaxSize int // max. size of file in MB
MaxBackup int //
MaxAge int
Debug bool
TerminalOut bool
}
func DefaultConfig() *Config {
return &Config{
Debug: false,
TerminalOut: false,
MaxSize: 1,
MaxBackup: 3,
MaxAge: 28,
}
}

View File

@@ -7,6 +7,7 @@ import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
type Level zapcore.Level
@@ -24,14 +25,14 @@ type Logger struct {
debugging bool
}
func NewLogger(name string, debug bool) (*Logger, error) {
func NewLogger(file string, cfg *Config) (*Logger, error) {
if name == "" {
name = "NewLogger"
if cfg == nil {
cfg = DefaultConfig()
}
file, err := os.OpenFile(fmt.Sprintf("%s.log", name), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
if file == "" {
file = "NewLogger.log"
}
encoderConfig := zap.NewProductionEncoderConfig()
@@ -41,13 +42,42 @@ func NewLogger(name string, debug bool) (*Logger, error) {
}
encoder := zapcore.NewJSONEncoder(encoderConfig)
fileSyncer := zapcore.AddSync(&lumberjack.Logger{
Filename: file,
MaxSize: 1, // megabytes
MaxBackups: 3,
MaxAge: 28, // days
})
// Create core list
var cores []zapcore.Core
// File core (always added)
cores = append(cores, zapcore.NewCore(encoder, fileSyncer, zapcore.InfoLevel))
// Optional stdout core
if cfg.TerminalOut {
stdoutSyncer := zapcore.AddSync(zapcore.Lock(os.Stdout))
cores = append(cores, zapcore.NewCore(encoder, stdoutSyncer, zapcore.InfoLevel))
}
combinedCore := zapcore.NewTee(cores...)
// If debugging, add a separate debug core (to both file and stdout if requested)
var debugCores []zapcore.Core
debugCores = append(debugCores, zapcore.NewCore(encoder, fileSyncer, zapcore.DebugLevel))
if cfg.TerminalOut {
stdoutSyncer := zapcore.AddSync(zapcore.Lock(os.Stdout))
debugCores = append(debugCores, zapcore.NewCore(encoder, stdoutSyncer, zapcore.DebugLevel))
}
debugCore := zapcore.NewTee(debugCores...)
// Build the logger
return &Logger{
log: zap.New(zapcore.NewCore(encoder, zapcore.AddSync(file), zapcore.InfoLevel)),
debug: zap.New(zapcore.NewCore(encoder, zapcore.AddSync(file), zapcore.DebugLevel)),
debugging: debug,
},
nil
log: zap.New(combinedCore),
debug: zap.New(debugCore),
debugging: cfg.Debug,
}, nil
}
func (l *Logger) Info(caller, msg string) {
@@ -58,8 +88,8 @@ func (l *Logger) Warning(caller, msg string) {
l.log.Warn(msg, zap.String("caller", caller))
}
func (l *Logger) Error(caller, msg string) {
l.log.Error(msg, zap.String("caller", caller))
func (l *Logger) Error(caller string, msg any) {
l.log.Error(fmt.Sprint(msg), zap.String("caller", caller))
}
func (l *Logger) Debug(caller, msg string) {