初步完成&测试可用

This commit is contained in:
Yun
2024-01-23 00:12:08 +08:00
parent fc485d8670
commit 10ecbce64f
6 changed files with 148 additions and 78 deletions
+30 -44
View File
@@ -4,11 +4,6 @@ package loggerx
// lastTime:2023年6月30日21:28:04
// desc: 日志封装类
// 优化方向
// 可以写盘的时候添加缓存,但是有个难点就是如果采用缓存的方式必须保证这个是最后关闭的,如果不是则退出的时候会丢失日志(写在缓存里还没刷盘)
// TODO:自动清除过期日志
import (
"bytes"
"context"
@@ -26,10 +21,15 @@ import (
// 需要实现io.Writer接口
type Logger struct {
filePath *sync.Map // filePath
mu *sync.Mutex
option loggerOption
channel string
}
type filePath struct {
file *os.File
fileName string
mu sync.Mutex
// channel string
}
func NewLogger(opts ...Option) *Logger {
@@ -38,55 +38,41 @@ func NewLogger(opts ...Option) *Logger {
apply(&opt)
}
l := &Logger{}
// 打开文件
err := l.createNewFile(true)
if err != nil {
panic(err)
l := &Logger{
filePath: &sync.Map{},
mu: &sync.Mutex{},
option: opt,
}
log.SetOutput(l)
log.SetFlags(log.LstdFlags | log.Llongfile | log.Lmicroseconds) // log.Lshortfile | log.LUTC
// 保存Gin日志写入到文件+控制台
gin.DefaultWriter = io.MultiWriter(l, os.Stdout)
gin.DefaultErrorWriter = io.MultiWriter(l, os.Stdout)
// 赋值前缀
if prefix != "" {
log.SetPrefix(fmt.Sprintf("[%s]", prefix))
if opt.isGinLog {
gin.DefaultWriter = io.MultiWriter(l, os.Stdout)
gin.DefaultErrorWriter = io.MultiWriter(l, os.Stdout)
}
return l
}
// func (l *Logger) Channel(ch string) (r *Logger) {
// rr := l
// rr.channel = ch
// return rr
// }
// 强制刷盘
func (l *Logger) MustSync() {
l.filePath.Range(func(key, value any) bool {
f := value.(*filePath)
f.file.Sync()
return true
})
}
// 超时删除
func (l *Logger) Channel(ch string) (r *Logger) {
rr := *l
rr.channel = ch
return &rr
}
// 实现io.Writer接口
func (l *Logger) Write(b []byte) (n int, err error) {
if l.file == nil {
// 新建一个file连接
l.createNewFile(false)
}
if l.fileName != nowFileName() {
l.createNewFile(false)
}
n, err = l.file.Write(b)
if err == nil && n < len(b) {
err = io.ErrShortWrite
}
if err != nil {
// 强制更新
l.createNewFile(true)
}
return n, err
return l.write("info", b)
}
func (l *Logger) Info(ctx context.Context, v ...any) {