修正 ms 显示格式,File Rotating 模式支持续写,如果文件已存在不对上次内容进行覆盖,而是从文件结尾继续往下写,或直接写下一个文件。

Signed-off-by: rick.chan <cy@haoan119.com>
This commit is contained in:
rick.chan 2025-04-01 14:34:18 +08:00
parent ac9c772fb6
commit cb55fecbc6
4 changed files with 21 additions and 9 deletions

2
.gitignore vendored
View File

@ -1 +1,3 @@
.vscode/settings.json
*.log
*.log.*

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Simple Log
A very simple log system(golang).

View File

@ -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)
}
}

View File

@ -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 {