jylog.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package config
  2. /**
  3. 日志文件自动切换,默认保留15天内日志
  4. **/
  5. import (
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "regexp"
  10. "time"
  11. "github.com/go-xweb/xweb"
  12. "github.com/robfig/cron"
  13. )
  14. // 日志格式
  15. var fileReg = regexp.MustCompile("^(\\d{4}_[0-9_]{14})\\.log$")
  16. // 当前日志文件句柄
  17. var LogFile *os.File
  18. // 时间格式
  19. var FMT = "2006_01_02_15_04_05"
  20. // 日志目录
  21. var LogPath = "./jylog"
  22. func JyLogInit() {
  23. os.Mkdir(LogPath, os.ModePerm)
  24. //默认保留15天内的日志,-1为永久保留
  25. initLog(15)
  26. }
  27. func initLog(saveDay int) {
  28. go logfile()
  29. task := cron.New()
  30. task.Start()
  31. task.AddFunc("0 0 0 * * ?", func() {
  32. go logfile()
  33. time.Sleep(50 * time.Second)
  34. if saveDay > 0 {
  35. filepath.Walk(LogPath, func(path string, info os.FileInfo, err error) error {
  36. str := fileReg.FindStringSubmatch(info.Name())
  37. if len(str) == 2 {
  38. t, er := time.ParseInLocation(FMT, str[1], time.Local)
  39. if er == nil {
  40. if (time.Now().Unix()-t.Unix())/86400 > int64(saveDay) {
  41. log.Println("delete log file:", path, os.Remove(path))
  42. }
  43. }
  44. }
  45. return nil
  46. })
  47. }
  48. })
  49. }
  50. // 创建并切换输出文件
  51. func logfile() {
  52. now := time.Now().Format(FMT)
  53. file, _ := os.Create(LogPath + "/" + now + ".log")
  54. log.SetOutput(file)
  55. xweb.RootApp().Logger.SetOutput(file)
  56. go func(file *os.File) {
  57. time.Sleep(5 * time.Second)
  58. if LogFile != nil {
  59. LogFile.Close()
  60. }
  61. LogFile = file
  62. }(file)
  63. }