94 lines
2.1 KiB
Go
94 lines
2.1 KiB
Go
package logger
|
|
|
|
import (
|
|
"os"
|
|
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
)
|
|
|
|
type ZapLogger struct {
|
|
logger *zap.Logger
|
|
}
|
|
|
|
func NewZapLogger() *ZapLogger {
|
|
atomicLevel := zap.NewAtomicLevel()
|
|
atomicLevel.SetLevel(zapcore.DebugLevel)
|
|
|
|
encoderConfig := zap.NewProductionEncoderConfig()
|
|
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
encoderConfig.TimeKey = "timestamp"
|
|
|
|
core := zapcore.NewCore(
|
|
zapcore.NewJSONEncoder(encoderConfig),
|
|
zapcore.Lock(os.Stdout),
|
|
atomicLevel,
|
|
)
|
|
|
|
return &ZapLogger{
|
|
logger: zap.New(core),
|
|
}
|
|
}
|
|
|
|
func (l *ZapLogger) GetZap() *zap.Logger {
|
|
return l.logger
|
|
}
|
|
|
|
func (l *ZapLogger) Debug(msg string, fields ...map[string]interface{}) {
|
|
l.log(zap.DebugLevel, msg, fields...)
|
|
}
|
|
|
|
func (l *ZapLogger) Info(msg string, fields ...map[string]interface{}) {
|
|
l.log(zap.InfoLevel, msg, fields...)
|
|
}
|
|
|
|
func (l *ZapLogger) Warn(msg string, fields ...map[string]interface{}) {
|
|
l.log(zap.WarnLevel, msg, fields...)
|
|
}
|
|
|
|
func (l *ZapLogger) Error(msg string, fields ...map[string]interface{}) {
|
|
l.log(zap.ErrorLevel, msg, fields...)
|
|
}
|
|
|
|
func (l *ZapLogger) Fatal(msg string, fields ...map[string]interface{}) {
|
|
l.log(zap.FatalLevel, msg, fields...)
|
|
}
|
|
|
|
func (l *ZapLogger) log(level zapcore.Level, msg string, fields ...map[string]interface{}) {
|
|
if len(fields) == 0 || fields[0] == nil {
|
|
switch level {
|
|
case zap.DebugLevel:
|
|
l.logger.Debug(msg)
|
|
case zap.InfoLevel:
|
|
l.logger.Info(msg)
|
|
case zap.WarnLevel:
|
|
l.logger.Warn(msg)
|
|
case zap.ErrorLevel:
|
|
l.logger.Error(msg)
|
|
case zap.FatalLevel:
|
|
l.logger.Fatal(msg)
|
|
}
|
|
} else {
|
|
zapFields := convertMapToZapFields(fields[0])
|
|
switch level {
|
|
case zap.DebugLevel:
|
|
l.logger.Debug(msg, zapFields...)
|
|
case zap.InfoLevel:
|
|
l.logger.Info(msg, zapFields...)
|
|
case zap.WarnLevel:
|
|
l.logger.Warn(msg, zapFields...)
|
|
case zap.ErrorLevel:
|
|
l.logger.Error(msg, zapFields...)
|
|
case zap.FatalLevel:
|
|
l.logger.Fatal(msg, zapFields...)
|
|
}
|
|
}
|
|
}
|
|
|
|
func convertMapToZapFields(fields map[string]interface{}) []zap.Field {
|
|
zapFields := make([]zap.Field, 0, len(fields))
|
|
for key, value := range fields {
|
|
zapFields = append(zapFields, zap.Any(key, value))
|
|
}
|
|
return zapFields
|
|
}
|