package hook import ( "context" "time" "go.uber.org/zap" "gorm.io/gorm/logger" ) type CustomLogger struct { *zap.Logger } // LogMode 设置日志级别 func (cl *CustomLogger) LogMode(level logger.LogLevel) logger.Interface { return cl } // Info 记录信息 func (cl *CustomLogger) Info(ctx context.Context, msg string, data ...interface{}) { cl.Logger.Info(msg, zap.Any("data", data)) } // Warn 记录警告 func (cl *CustomLogger) Warn(ctx context.Context, msg string, data ...interface{}) { cl.Logger.Warn(msg, zap.Any("data", data)) } // Error 记录错误 func (cl *CustomLogger) Error(ctx context.Context, msg string, data ...interface{}) { cl.Logger.Error(msg, zap.Any("data", data)) } // Trace 记录跟踪信 func (cl *CustomLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { elapsed := time.Since(begin) sql, rows := fc() // Assign the returned values to variables fields := []zap.Field{ zap.String("sql", sql), zap.Int64("rows", rows), zap.Error(err), zap.Duration("took", elapsed), } if err != nil { cl.Logger.Error("sql:", fields...) } else if elapsed > 1*time.Second { cl.Logger.Warn("sql:", fields...) } else { // cl.Logger.Info("sql:", fields...) } }