支持配置是否打印到文件

This commit is contained in:
Yun
2024-07-09 15:36:11 +08:00
parent d41516d05d
commit 70699e9701
4 changed files with 58 additions and 21 deletions
+23
View File
@@ -0,0 +1,23 @@
package main
import (
"context"
"github.com/yuninks/loggerx"
)
func main() {
ctx := context.Background()
log := loggerx.NewLogger(ctx,
// loggerx.SetPrintFile(false),
loggerx.SetToConsole(),
)
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
log.Info(ctx, "哈哈哈2")
}
+17 -8
View File
@@ -12,6 +12,7 @@ type loggerOption struct {
dir string // 文件目录
isGinLog bool
isGid bool
isPrintFile bool
traceField string // trace字段
errorToInfo bool // 错误日志是否写入info日志
days int // 日志保存天数
@@ -23,14 +24,15 @@ type loggerOption struct {
func defaultOptions() loggerOption {
return loggerOption{
isGinLog: true,
isGid: true,
format: "json",
dir: "./log",
traceField: "trace_id",
days: 7,
fileSplit: FileSplitTimeE,
timeZone: time.Local,
isGinLog: true,
isGid: true,
isPrintFile: true,
format: "json",
dir: "./log",
traceField: "trace_id",
days: 7,
fileSplit: FileSplitTimeE,
timeZone: time.Local,
}
}
@@ -71,6 +73,13 @@ func SetFormat(format string) Option {
}
}
// 设置是否打印到文件
func SetPrintFile(print bool) Option {
return func(o *loggerOption) {
o.isPrintFile = print
}
}
// 是否保存gin的日志
func SetGinLog(open bool) Option {
return func(o *loggerOption) {
+2
View File
@@ -9,6 +9,8 @@ log.Println("ddddd")
```
# 用法
# 开发计划
+16 -13
View File
@@ -5,20 +5,23 @@ import (
)
func (l *Logger) write(event string, b []byte) (n int, err error) {
f, err := l.getFile(event, false)
if err != nil {
return 0, err
}
n, err = f.Write(b)
if err == nil && n < len(b) {
err = io.ErrShortWrite
}
if err != nil {
// 强制更新 & 再次写入
f, err := l.getFile(event, true)
if err == nil {
f.Write(b)
if l.option.isPrintFile {
f, err := l.getFile(event, false)
if err != nil {
return 0, err
}
n, err = f.Write(b)
if err == nil && n < len(b) {
err = io.ErrShortWrite
}
if err != nil {
// 强制更新 & 再次写入
f, err := l.getFile(event, true)
if err == nil {
f.Write(b)
}
}
}