From ac9c772fb682c6f298efab10eef066d410dd0189 Mon Sep 17 00:00:00 2001 From: "rick.chan" Date: Tue, 1 Apr 2025 13:54:55 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=81=E7=A7=BB=E9=A1=B9=E7=9B=AE=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: rick.chan --- .gitignore | 1 + demo/main.go | 11 +++++++++++ filehandler.go | 33 +++++++++++++++++++++++++++++++++ go.mod | 2 +- 4 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 demo/main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6f9a44 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode/settings.json diff --git a/demo/main.go b/demo/main.go new file mode 100644 index 0000000..e5e5532 --- /dev/null +++ b/demo/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "github.com/lion187chen/simplelog" +) + +var sl *simplelog.SimpleLog + +func main() { + sl = new(simplelog.SimpleLog).InitRotating("./log/MS.log", 1024*1024*2, 100, simplelog.LevelTrace) +} diff --git a/filehandler.go b/filehandler.go index 2d0d898..8486887 100644 --- a/filehandler.go +++ b/filehandler.go @@ -7,6 +7,16 @@ import ( "time" ) +func isFileExist(filename string) bool { + info, e := os.Stat(filename) + + if e == nil { + return !info.IsDir() + } else { + return os.IsExist(e) + } +} + // FileHandler writes log to a file. type FileHandler struct { fd *os.File @@ -48,6 +58,25 @@ type RotatingFileHandler struct { } func (h *RotatingFileHandler) InitRotating(name string, maxBytes int, backupCount int) (*RotatingFileHandler, error) { + if isFileExist(name) { + var err error + h.fd, err = os.OpenFile(name, os.O_CREATE|os.O_RDONLY, 0666) + if err != nil { + return nil, err + } + f, err := h.fd.Stat() + if err != nil { + h.fd.Close() + return nil, err + } + if f.Size() > 0 { + h._doRollover() + return h, nil + } else { + h.fd.Close() + } + } + dir := path.Dir(name) os.MkdirAll(dir, 0777) @@ -106,6 +135,10 @@ func (h *RotatingFileHandler) doRollover() { return } + h._doRollover() +} + +func (h *RotatingFileHandler) _doRollover() { if h.backupCount > 0 { h.fd.Close() diff --git a/go.mod b/go.mod index a554d94..58a2a1b 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module blacktea.cpolar.cn/OrgGo/simplelog +module github.com/lion187chen/simplelog go 1.21.0