添加过期移除

This commit is contained in:
Yun
2024-01-23 13:37:51 +08:00
parent 10ecbce64f
commit 60ad89f164
6 changed files with 68 additions and 7 deletions
-5
View File
@@ -1,5 +0,0 @@
package loggerx
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"time"
)
// 日志文件的计算
// 文件操作
// 获取最新的文件名
func (l *Logger) nowFileName(event string) string {
+4
View File
@@ -52,6 +52,10 @@ func NewLogger(opts ...Option) *Logger {
gin.DefaultWriter = io.MultiWriter(l, os.Stdout)
gin.DefaultErrorWriter = io.MultiWriter(l, os.Stdout)
}
// 日志删除
go l.delete()
return l
}
+2
View File
@@ -3,6 +3,7 @@ package loggerx_test
import (
"context"
"testing"
"time"
"code.yun.ink/pkg/loggerx"
)
@@ -20,4 +21,5 @@ func TestLogger(t *testing.T) {
l.Info(context.Background(), "test info")
time.Sleep(time.Second * 2)
}
+10 -1
View File
@@ -7,7 +7,8 @@ type loggerOption struct {
isGinLog bool
isGid bool
traceField string // trace字段
errorToInfo bool //
errorToInfo bool // 错误日志是否写入info日志
days int // 日志保存天数
}
func defaultOptions() loggerOption {
@@ -15,6 +16,7 @@ func defaultOptions() loggerOption {
format: "json",
dir: "./log",
traceField: "trace_id",
days: 7,
}
}
@@ -69,6 +71,13 @@ func SetGID() Option {
}
}
// 日志保存天数
func SetDays(days int) Option {
return func(o *loggerOption) {
o.days = days
}
}
// 文件切割规则
// 1.文件大小
// 2.时间A(年/月/日/时)
+51
View File
@@ -0,0 +1,51 @@
package loggerx
import (
"fmt"
"os"
"path/filepath"
"time"
)
func (l *Logger) delete() {
err := filepath.Walk(l.option.dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return err
}
if l.option.days <= 0 {
l.option.days = 1
}
// 判断最后修改时间是否大于3天
if info.ModTime().After(time.Now().AddDate(0, 0, -l.option.days)) {
return nil
}
if info.IsDir() {
if !isEmptyDir(path) {
return nil
}
}
ext := filepath.Ext(path)
if ext == ".log" {
return nil
}
// 删除文件
fmt.Println("删除文件", path)
return os.Remove(path)
})
if err != nil {
fmt.Println(err)
}
}
func isEmptyDir(path string) bool {
files, err := os.ReadDir(path)
if err != nil {
fmt.Println(err)
return false
}
return len(files) == 0 // 文件夹为空
}