Skip to content

Commit

Permalink
👔 update: rotatefile - config add new field DebugMode for dev
Browse files Browse the repository at this point in the history
- add more unit test for rotate by time
  • Loading branch information
inhere committed Jul 27, 2023
1 parent b8c0984 commit 21d1056
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 28 deletions.
2 changes: 1 addition & 1 deletion _example/issue100/issue100_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,5 @@ func TestSlog(t *testing.T) {
}
end = time.Now().UnixNano()
fmt.Printf("\n slog format \n total cost %d ns\n avg cost %d ns \n count %d \n", end-start, (end-start)/int64(count), count)
logs.MustFlush()
logs.MustClose()
}
11 changes: 11 additions & 0 deletions rotatefile/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"time"

"github.com/gookit/goutil/stdio"
"github.com/gookit/goutil/timex"
)

Expand Down Expand Up @@ -190,6 +191,9 @@ type Config struct {

// TimeClock for rotate file by time.
TimeClock Clocker

// DebugMode for debug on development.
DebugMode bool
}

func (c *Config) backupDuration() time.Duration {
Expand All @@ -213,6 +217,13 @@ func (c *Config) Create() (*Writer, error) { return NewWriter(c) }
// IsMode check rotate mode
func (c *Config) IsMode(m RotateMode) bool { return c.RotateMode == m }

// Debug print debug message on development
func (c *Config) Debug(vs ...any) {
if c.DebugMode {
stdio.WriteString("[rotate-file.DEBUG] " + fmt.Sprintln(vs...))
}
}

var (
// DefaultFilePerm perm and flags for create log file
DefaultFilePerm os.FileMode = 0664
Expand Down
12 changes: 4 additions & 8 deletions rotatefile/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func (d *Writer) doRotate() (err error) {
err = d.rotatingByTime()
}

// async clean backup files
// async clean backup files. TODO only call on file rotated.
d.asyncClean()
return
}
Expand Down Expand Up @@ -271,7 +271,7 @@ func (d *Writer) asyncClean() {
if d.cleanCh != nil {
select {
case d.cleanCh <- struct{}{}:
d.cfg.Debug("clean old files signal sent")
d.cfg.Debug("signal sent start clean old files ")
default: // skip on blocking
d.cfg.Debug("clean old files signal blocked, skip")
}
Expand Down Expand Up @@ -389,14 +389,10 @@ func (d *Writer) Clean() (err error) {
func (d *Writer) buildFilterFns(fileName string) []fsutil.FilterFunc {
filterFns := []fsutil.FilterFunc{
fsutil.OnlyFindFile,
// filter by name. should match like error.log.*
// filter by name. match pattern like: error.log.*
// eg: error.log.xx, error.log.xx.gz
func(fPath string, ent fs.DirEntry) bool {
ok, err := path.Match(fileName+".*", ent.Name())
if err != nil {
printErrln("rotatefile: match old file error:", err)
return false // skip, not handle
}
ok, _ := path.Match(fileName+".*", ent.Name())
return ok
},
}
Expand Down
49 changes: 30 additions & 19 deletions rotatefile/writer_test.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,17 @@
package rotatefile_test

import (
"log"
"path/filepath"
"testing"
"time"

"github.com/gookit/goutil"
"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/fsutil"
"github.com/gookit/goutil/mathutil"
"github.com/gookit/goutil/testutil/assert"
"github.com/gookit/slog/rotatefile"
)

func TestMain(m *testing.M) {
goutil.PanicErr(fsutil.RemoveSub("./testdata", fsutil.ExcludeNames(".keep")))
m.Run()
}

func ExampleNewWriter_on_other_logger() {
logFile := "testdata/another_logger.log"
writer, err := rotatefile.NewConfig(logFile).Create()
if err != nil {
panic(err)
}

log.SetOutput(writer)
log.Println("log message")
}

func TestNewWriter(t *testing.T) {
testFile := "testdata/test_writer.log"
assert.NoErr(t, fsutil.DeleteIfExist(testFile))
Expand Down Expand Up @@ -83,6 +66,31 @@ func TestWriter_Rotate_modeCreate(t *testing.T) {
assert.NoErr(t, err)
}

func TestWriter_rotateByTime(t *testing.T) {
logfile := "testdata/rotate-by-time.log"
c := rotatefile.NewConfig(logfile).With(func(c *rotatefile.Config) {
c.DebugMode = true
c.Compress = true
c.RotateTime = rotatefile.EverySecond * 2
})

w, err := c.Create()
assert.NoErr(t, err)
defer func() {
_ = w.Close()
}()

for i := 0; i < 5; i++ {
_, err = w.WriteString("[INFO] this is a log message, idx=" + mathutil.String(i) + "\n")
assert.NoErr(t, err)
time.Sleep(time.Second)
}

files := fsutil.Glob(logfile + ".*")
dump.P(files)

}

func TestWriter_Clean(t *testing.T) {
logfile := "testdata/writer_clean.log"

Expand All @@ -91,6 +99,9 @@ func TestWriter_Clean(t *testing.T) {

wr, err := c.Create()
assert.NoErr(t, err)
defer func() {
_ = wr.Close()
}()

for i := 0; i < 20; i++ {
_, err = wr.WriteString("[INFO] this is a log message, idx=" + mathutil.String(i) + "\n")
Expand All @@ -101,7 +112,7 @@ func TestWriter_Clean(t *testing.T) {
_, err = wr.WriteString("hi\n")
assert.NoErr(t, err)

files := fsutil.Glob("testdata/writer_clean.log.*")
files := fsutil.Glob(logfile + ".*")
dump.P(files)

// test clean error
Expand Down

0 comments on commit 21d1056

Please sign in to comment.