Skip to content

Commit

Permalink
ensure folder when file writer rotating
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Oct 21, 2024
1 parent 247534a commit d6365b6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log

import (
"crypto/md5"
"errors"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -155,7 +156,14 @@ func (w *FileWriter) rotate() (err error) {
var file *os.File
file, err = os.OpenFile(w.fileargs(timeNow()))
if err != nil {
return err
if errors.Is(err, os.ErrNotExist) && w.EnsureFolder {
if err = os.MkdirAll(filepath.Dir(w.Filename), 0755); err == nil {
file, err = os.OpenFile(w.fileargs(timeNow()))
}
}
if err != nil {
return err
}
}
if w.file != nil {
w.file.Close()
Expand Down
12 changes: 12 additions & 0 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,18 @@ func TestFileWriterEnsureFolder(t *testing.T) {
t.Logf("file writer return error: %+v", err)
}

remove(filepath.Dir(filename))

_, err = fmt.Fprint(w, text1)
if err != nil {
t.Logf("file writer return error: %+v", err)
}

err = w.Rotate()
if err != nil {
t.Logf("file writer rotate error: %+v", err)
}

_, err = fmt.Fprint(w, text2)
if err != nil {
t.Logf("file writer return error: %+v", err)
Expand Down

0 comments on commit d6365b6

Please sign in to comment.