Skip to content

Commit

Permalink
update: 文件close
Browse files Browse the repository at this point in the history
  • Loading branch information
SliverHorn committed Aug 13, 2023
1 parent a9321ad commit f0c7c22
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 26 deletions.
23 changes: 0 additions & 23 deletions cleaner.go

This file was deleted.

22 changes: 19 additions & 3 deletions rotatelogs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (
// Rotate represents a log file that gets
// automatically rotated as you write to it.
type Rotate struct {
filename string // 当前文件名称
clock Clock // 时间
out *os.File // 文件句柄
business *os.File // 文件句柄
mutex *sync.RWMutex // 读写锁
maxAge time.Duration // 最大保存时间
pattern *strftime.Strftime // 时间格式
Expand Down Expand Up @@ -48,7 +48,10 @@ func New(p string, options ...Option) (*Rotate, error) {
// automatically rotated, and also purged if necessary.
func (r *Rotate) Write(bytes []byte) (n int, err error) {
r.mutex.Lock() // Guard against concurrent writes
defer r.mutex.Unlock()
defer func() {
r.mutex.Unlock()
r.Close()
}()
var out io.Writer
if strings.Contains(string(bytes), "business") {
var compile *regexp.Regexp
Expand Down Expand Up @@ -101,6 +104,7 @@ func (r *Rotate) getBusinessWriter(business string) (io.Writer, error) {
if err != nil {
return nil, err
}
r.business = out
return out, nil
}

Expand All @@ -113,6 +117,18 @@ func (r *Rotate) getWriter() (io.Writer, error) {
}
_ = r.out.Close()
r.out = out
r.filename = filename
return out, nil
}

func (r *Rotate) Close() {
r.mutex.Lock() // Guard against concurrent writes
defer r.mutex.Unlock()
if r.out != nil {
_ = r.out.Close()
r.out = nil
}
if r.business != nil {
_ = r.business.Close()
r.business = nil
}
}

0 comments on commit f0c7c22

Please sign in to comment.