Skip to content

Commit

Permalink
feat: add rotate at midnight
Browse files Browse the repository at this point in the history
  • Loading branch information
qazwsxedckll committed Apr 9, 2024
1 parent 996f8af commit 6e66c8a
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions rotate_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ type RotateFile struct {
filepath string
file *os.File

rotateSize int
rotateInterval time.Duration
checkEveryN int
rotateSize int
rotateInterval time.Duration
rotateAtMidnight bool
checkEveryN int

written int
lastRotate time.Time
Expand All @@ -35,10 +36,11 @@ func NewRotateFile(directory string, basename string, rotateSize int, opts ...Op
path := filepath.Join(directory, basename)

rf := &RotateFile{
filepath: path,
rotateSize: rotateSize,
rotateInterval: time.Hour * 24,
checkEveryN: 1024,
filepath: path,
rotateSize: rotateSize,
rotateInterval: time.Hour * 24,
rotateAtMidnight: false,
checkEveryN: 1024,
}

for _, opt := range opts {
Expand All @@ -62,8 +64,14 @@ func (r *RotateFile) Write(p []byte) (int, error) {
r.count++
if r.count >= r.checkEveryN {
r.count = 0
if time.Now().After(r.lastRotate.Add(r.rotateInterval)) {
r.rotate()
if r.rotateAtMidnight {
if time.Now().Day() != r.lastRotate.Day() {
r.rotate()
}
} else {
if time.Now().After(r.lastRotate.Add(r.rotateInterval)) {
r.rotate()
}
}
}
}
Expand Down Expand Up @@ -112,3 +120,10 @@ func WithRotateInterval(d time.Duration) Option {
r.rotateInterval = d
}
}

// WithRotateAtMidnight will suppress the rotateInterval
func WithRotateAtMidnight() Option {
return func(r *RotateFile) {
r.rotateAtMidnight = true
}
}

0 comments on commit 6e66c8a

Please sign in to comment.