Log

gorm自制日志

May 8, 2024
Go, Gorm, Mysql, Log

第三方包 # gorm.io/gorm/logger 示例 # package boot import ( "context" "fmt" "io/ioutil" "log" "os" "time" "github.com/xiaohubai/alpha/config" "go.uber.org/zap" "gorm.io/gorm/logger" "gorm.io/gorm/utils" ) type cfg struct { SlowThreshold time.Duration Colorful bool LogLevel logger.LogLevel } type traceRecorder struct { logger.Interface BeginAt time.Time SQL string RowsAffected int64 Err error } func (t traceRecorder) New() *traceRecorder { return &traceRecorder{Interface: t.Interface, BeginAt: time.Now()} } func (t *traceRecorder) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { t. ...

zap使用

May 8, 2024
Go, Log, Zap

第三方包 # go.uber.org/zap zap记录日志 # uber 开源的高性能日志库,面向高性能 package boot import ( "fmt" "path" "time" "github.com/xiaohubai/alpha/config" zaprotatelogs "github.com/lestrrat-go/file-rotatelogs" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var level zapcore.Level // Zap 日志组件 func Zap() (logger *zap.Logger) { level = zap.InfoLevel logger = zap.New(getEncoderCore()) logger.WithOptions(zap.AddCaller()) return logger } func getEncoderCore() (core zapcore.Core) { writer, err := GetWriteSyncer() // 使用file-rotatelogs进行日志分割 if err != nil { panic(fmt.Errorf("Get Write Syncer Failed err:%v", err.Error())) } return zapcore.NewCore(zapcore.NewJSONEncoder(getEncoderConfig()), writer, level) } func getEncoderConfig() (cfg zapcore. ...