rotatefile.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package file
  2. import (
  3. "io"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. rotatelogs "github.com/lestrrat/go-file-rotatelogs"
  8. )
  9. // 参考 https://github.com/nacos-group/nacos-sdk-go/blob/v1.0.4/common/logger/logger.go#L130
  10. type RotateWriterConfig struct {
  11. Pattern string `json:"pattern"`
  12. FileName string `json:"file_path"`
  13. MaxAge time.Duration `json:"max_age"`
  14. RotateDuration time.Duration `json:"rotate_time"`
  15. }
  16. func NewDefaultRotateWriter(fileName string) RotateWriterConfig {
  17. return RotateWriterConfig{
  18. FileName: fileName,
  19. MaxAge: time.Hour * 24 * 30,
  20. RotateDuration: time.Hour * 24,
  21. Pattern: "%Y%m%d%H%M",
  22. }
  23. }
  24. func (config RotateWriterConfig) NewWriter() (io.Writer, error) {
  25. fileSimpleName := filepath.Base(config.FileName)
  26. outputPath := filepath.Dir(config.FileName) + string(os.PathSeparator)
  27. return rotatelogs.New(filepath.Join(outputPath, fileSimpleName+"-"+config.Pattern),
  28. rotatelogs.WithRotationTime(config.RotateDuration), rotatelogs.WithMaxAge(config.MaxAge),
  29. rotatelogs.WithLinkName(filepath.Join(outputPath, fileSimpleName)))
  30. }