mg-transport-core/core/logger/default.go

74 lines
1.7 KiB
Go
Raw Normal View History

2023-10-18 14:27:23 +03:00
package logger
import (
2023-11-24 15:23:07 +03:00
"strconv"
2023-10-18 14:27:23 +03:00
2023-11-24 15:23:07 +03:00
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
2023-10-18 14:27:23 +03:00
2023-11-24 15:23:07 +03:00
type Logger interface {
With(fields ...zap.Field) Logger
WithLazy(fields ...zap.Field) Logger
Level() zapcore.Level
Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry
Log(lvl zapcore.Level, msg string, fields ...zap.Field)
Debug(msg string, fields ...zap.Field)
Info(msg string, fields ...zap.Field)
Warn(msg string, fields ...zap.Field)
Error(msg string, fields ...zap.Field)
DPanic(msg string, fields ...zap.Field)
Panic(msg string, fields ...zap.Field)
Fatal(msg string, fields ...zap.Field)
2024-01-19 13:17:04 +03:00
ForHandler(handler any) Logger
ForConnection(conn any) Logger
ForAccount(acc any) Logger
2023-11-24 15:23:07 +03:00
Sync() error
2023-10-18 14:27:23 +03:00
}
2023-11-24 15:23:07 +03:00
type Default struct {
*zap.Logger
2023-10-18 14:27:23 +03:00
}
2024-04-10 14:06:41 +03:00
func NewDefault(format string, debug bool) Logger {
2023-11-24 15:23:07 +03:00
return &Default{
2024-04-10 14:06:41 +03:00
Logger: NewZap(format, debug),
2023-11-24 15:23:07 +03:00
}
2023-10-18 14:27:23 +03:00
}
2023-11-24 15:23:07 +03:00
func (l *Default) With(fields ...zap.Field) Logger {
2024-01-19 14:48:18 +03:00
return l.clone(l.Logger.With(fields...))
2023-10-18 14:27:23 +03:00
}
2023-11-24 15:23:07 +03:00
func (l *Default) WithLazy(fields ...zap.Field) Logger {
2024-01-19 14:48:18 +03:00
return l.clone(l.Logger.WithLazy(fields...))
2023-10-18 14:27:23 +03:00
}
2024-01-19 13:17:04 +03:00
func (l *Default) ForHandler(handler any) Logger {
return l.WithLazy(zap.Any(HandlerAttr, handler))
}
func (l *Default) ForConnection(conn any) Logger {
return l.WithLazy(zap.Any(ConnectionAttr, conn))
}
func (l *Default) ForAccount(acc any) Logger {
return l.WithLazy(zap.Any(AccountAttr, acc))
2023-10-18 14:27:23 +03:00
}
2024-01-19 14:48:18 +03:00
func (l *Default) clone(log *zap.Logger) Logger {
return &Default{Logger: log}
}
2023-11-24 15:23:07 +03:00
func AnyZapFields(args []interface{}) []zap.Field {
fields := make([]zap.Field, len(args))
for i := 0; i < len(fields); i++ {
if val, ok := args[i].(zap.Field); ok {
fields[i] = val
continue
}
fields[i] = zap.Any("arg"+strconv.Itoa(i), args[i])
}
return fields
2023-10-18 14:27:23 +03:00
}