diff --git a/.gitignore b/.gitignore index c6f9a44..a1c29da 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .vscode/settings.json +*.log +*.log.* diff --git a/README.md b/README.md new file mode 100644 index 0000000..74427b4 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Simple Log + +A very simple log system(golang). diff --git a/demo/main.go b/demo/main.go index e5e5532..b101914 100644 --- a/demo/main.go +++ b/demo/main.go @@ -1,11 +1,17 @@ package main import ( + "time" + "github.com/lion187chen/simplelog" ) var sl *simplelog.SimpleLog func main() { - sl = new(simplelog.SimpleLog).InitRotating("./log/MS.log", 1024*1024*2, 100, simplelog.LevelTrace) + sl = new(simplelog.SimpleLog).InitRotating("./log/MS.log", 1024*10, 10, simplelog.LevelTrace) + for i := 0; i < 10000000; i++ { + sl.Debug("hello world") + time.Sleep(8 * time.Millisecond) + } } diff --git a/filehandler.go b/filehandler.go index 8486887..3ab2d8e 100644 --- a/filehandler.go +++ b/filehandler.go @@ -2,6 +2,7 @@ package simplelog import ( "fmt" + "io" "os" "path" "time" @@ -58,6 +59,10 @@ type RotatingFileHandler struct { } func (h *RotatingFileHandler) InitRotating(name string, maxBytes int, backupCount int) (*RotatingFileHandler, error) { + h.fileName = name + h.maxBytes = maxBytes + h.backupCount = backupCount + if isFileExist(name) { var err error h.fd, err = os.OpenFile(name, os.O_CREATE|os.O_RDONLY, 0666) @@ -69,12 +74,12 @@ func (h *RotatingFileHandler) InitRotating(name string, maxBytes int, backupCoun h.fd.Close() return nil, err } - if f.Size() > 0 { - h._doRollover() - return h, nil + if f.Size() < int64(h.maxBytes) { + h.fd.Seek(0, io.SeekEnd) } else { - h.fd.Close() + h._doRollover() } + return h, nil } dir := path.Dir(name) @@ -84,10 +89,6 @@ func (h *RotatingFileHandler) InitRotating(name string, maxBytes int, backupCoun return nil, fmt.Errorf("invalid max bytes") } - h.fileName = name - h.maxBytes = maxBytes - h.backupCount = backupCount - var err error h.fd, err = os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0666) if err != nil {