From d6365b69cc8f08120309c4886310077ae478a5cf Mon Sep 17 00:00:00 2001 From: phuslu Date: Mon, 21 Oct 2024 14:22:40 +0800 Subject: [PATCH] ensure folder when file writer rotating --- file.go | 10 +++++++++- file_test.go | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/file.go b/file.go index 234f060e..0e94d99e 100644 --- a/file.go +++ b/file.go @@ -2,6 +2,7 @@ package log import ( "crypto/md5" + "errors" "io" "os" "path/filepath" @@ -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() diff --git a/file_test.go b/file_test.go index 3665e265..9fbac846 100644 --- a/file_test.go +++ b/file_test.go @@ -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)