You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
877 B

2 years ago
  1. package log
  2. import (
  3. "fmt"
  4. "github.com/robfig/cron"
  5. "log"
  6. "sync"
  7. "time"
  8. )
  9. var (
  10. logPath string
  11. once sync.Once
  12. Spec = "@daily"
  13. )
  14. // RegisterRotationWithSpec set up crontab scheduler for log rotation
  15. //
  16. // spec, "* * * * * *"; "@daily"
  17. func RegisterRotationWithSpec(path, spec string) {
  18. if "" == spec {
  19. spec = Spec
  20. }
  21. listening(path, spec)
  22. }
  23. func RegisterRotation(path string) {
  24. listening(path, Spec)
  25. }
  26. func listening(path, spec string) {
  27. once.Do(func() {
  28. logPath = path
  29. rotate()
  30. go _listening(spec)
  31. })
  32. }
  33. func _listening(spec string) {
  34. _c := cron.New()
  35. if err := _c.AddFunc(spec, rotate); nil != err {
  36. panic(fmt.Sprintf("failed to establish crontab job: %s", err.Error()))
  37. } else {
  38. log.Println("log rotation started ...")
  39. }
  40. _c.Start()
  41. select {}
  42. }
  43. func rotate() {
  44. RotateLogger(New(logPath+time.Now().Format("2006-01-02"), logPath))
  45. }