learn lessions

This commit is contained in:
Adrian Zürcher
2025-04-16 09:36:50 +02:00
parent cdbeaf3940
commit 6f963ae0a4
2 changed files with 4 additions and 2 deletions

70
logging/logging.go Normal file
View File

@@ -0,0 +1,70 @@
package logging
import (
"fmt"
"os"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Level zapcore.Level
const (
Info Level = 0
Warning Level = 1
Error Level = 2
Debug Level = -1
)
type Logger struct {
log *zap.Logger
debug *zap.Logger
debugging bool
}
func NewLogger(name string, debug bool) (*Logger, error) {
if name == "" {
name = "NewLogger"
}
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
}
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.TimeKey = "timestamp"
encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02T15:04:05.000"))
}
encoder := zapcore.NewJSONEncoder(encoderConfig)
// 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
}
func (l *Logger) Info(caller, msg string) {
l.log.Info(msg, zap.String("caller", caller))
}
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) Debug(caller, msg string) {
if !l.debugging {
return
}
l.debug.Debug(msg, zap.String("caller", caller))
}