package utils import ( "crypto/rand" "fmt" "math" "os" "os/exec" "strings" "time" "github.com/sirupsen/logrus" ) // Logger 全局日志实例 var Logger *logrus.Logger // InitLogger 初始化日志系统 func InitLogger(logFile string, level logrus.Level) { Logger = logrus.New() Logger.SetLevel(level) // 设置日志格式 Logger.SetFormatter(&logrus.TextFormatter{ FullTimestamp: true, TimestampFormat: "2006-01-02 15:04:05", }) // 如果提供了日志文件,则输出到文件 if logFile != "" { file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err == nil { Logger.SetOutput(file) } else { Logger.Info("无法写入日志文件,使用标准输出") } } } // GenerateRandomData 生成指定大小的随机数据 func GenerateRandomData(size int) ([]byte, error) { data := make([]byte, size) _, err := rand.Read(data) if err != nil { return nil, err } return data, nil } // BytesToMB 将字节转换为MB func BytesToMB(bytes int) float64 { return float64(bytes) / (1024 * 1024) } // MBToBytes 将MB转换为字节 func MBToBytes(mb float64) int { return int(mb * 1024 * 1024) } // KBToBytes 将KB转换为字节 func KBToBytes(kb float64) int { return int(kb * 1024) } // FormatDuration 格式化持续时间 func FormatDuration(d time.Duration) string { if d < time.Minute { return fmt.Sprintf("%.2f秒", d.Seconds()) } else if d < time.Hour { minutes := math.Floor(d.Minutes()) seconds := d.Seconds() - minutes*60 return fmt.Sprintf("%.0f分%.2f秒", minutes, seconds) } else { hours := math.Floor(d.Hours()) minutes := math.Floor(d.Minutes()) - hours*60 seconds := d.Seconds() - hours*3600 - minutes*60 return fmt.Sprintf("%.0f时%.0f分%.2f秒", hours, minutes, seconds) } } // CalculatePercentage 计算百分比 func CalculatePercentage(part, total float64) float64 { if total == 0 { return 0 } return (part / total) * 100 } // ExecuteCommand 执行系统命令 func ExecuteCommand(command string, args ...string) (string, error) { cmd := exec.Command(command, args...) output, err := cmd.CombinedOutput() if err != nil { return string(output), err } return string(output), nil } // IsMounted 检查指定路径是否已挂载 func IsMounted(mountPoint string) bool { output, err := ExecuteCommand("mount") if err != nil { return false } return strings.Contains(output, mountPoint) } // FileExists 检查文件是否存在 func FileExists(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } // CreateDirIfNotExist 如果目录不存在则创建 func CreateDirIfNotExist(path string) error { if !FileExists(path) { return os.MkdirAll(path, 0755) } return nil } // CalculateWriteSpeed 计算写入速度 func CalculateWriteSpeed(bytesWritten int, duration time.Duration) float64 { if duration.Seconds() == 0 { return 0 } return BytesToMB(bytesWritten) / duration.Seconds() } // CalculateIOPS 计算IOPS func CalculateIOPS(operations int, duration time.Duration) float64 { if duration.Seconds() == 0 { return 0 } return float64(operations) / duration.Seconds() }