clean.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package logger
  2. import (
  3. "IotAdmin/core/logger"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. )
  10. // DeleteLogsOlderThan 删除比指定日期早的日志文件。
  11. // days 参数表示需要删除的日志文件是几天前的。
  12. func DeleteLogsOlderThan(path, suffix string, days int) error {
  13. threshold := time.Now().AddDate(0, 0, -days)
  14. files, err := filepath.Glob(filepath.Join(path, "*."+suffix)) // 假设日志文件以.log结尾
  15. if err != nil {
  16. return fmt.Errorf("failed to list files in %s: %w", path, err)
  17. }
  18. for _, file := range files {
  19. err2 := deleteFile(file, threshold)
  20. if err2 != nil {
  21. return err2
  22. }
  23. }
  24. return nil
  25. }
  26. // DeleteAllLogsOlderThan 删除比指定日期早的日志文件(包括子目录下)。
  27. // days 参数表示需要删除的日志文件是几天前的。
  28. func DeleteAllLogsOlderThan(path, suffix string, days int) error {
  29. threshold := time.Now().AddDate(0, 0, 0)
  30. files, err := recursivelyFindFiles(path, suffix)
  31. if err != nil {
  32. return fmt.Errorf("failed to list files in %s: %w", path, err)
  33. }
  34. for _, file := range files {
  35. err2 := deleteFile(file, threshold)
  36. if err2 != nil {
  37. return err2
  38. }
  39. }
  40. return nil
  41. }
  42. func deleteFile(file string, threshold time.Time) error {
  43. fileInfo, err := os.Stat(file)
  44. if err != nil {
  45. if os.IsNotExist(err) {
  46. logger.Errorf("File %s does not exist\n", file)
  47. } else {
  48. return fmt.Errorf("failed to get info for %s: %w", file, err)
  49. }
  50. }
  51. // 检查文件修改时间是否早于阈值
  52. if fileInfo.ModTime().Before(threshold) {
  53. err = os.Remove(file)
  54. if err != nil {
  55. return fmt.Errorf("failed to delete %s: %w", file, err)
  56. }
  57. logger.Infof("删除日志文件: %s\n", file)
  58. }
  59. return nil
  60. }
  61. // recursivelyFindFiles walks the given directory tree and returns a slice of paths for files with the specified suffix.
  62. func recursivelyFindFiles(dirPath string, suffix string) ([]string, error) {
  63. var files []string
  64. err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
  65. if err != nil {
  66. return err
  67. }
  68. if !info.IsDir() && strings.HasSuffix(info.Name(), suffix) {
  69. files = append(files, path)
  70. }
  71. return nil
  72. })
  73. if err != nil {
  74. return nil, err
  75. }
  76. return files, nil
  77. }