diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..c71dc38 --- /dev/null +++ b/example/main.go @@ -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") +} diff --git a/options.go b/options.go index b169344..fb1cb9a 100644 --- a/options.go +++ b/options.go @@ -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) { diff --git a/readme.md b/readme.md index d2fca92..3eca248 100644 --- a/readme.md +++ b/readme.md @@ -9,6 +9,8 @@ log.Println("ddddd") ``` +# 用法 + # 开发计划 diff --git a/storage.go b/storage.go index 5025317..7e8e2da 100644 --- a/storage.go +++ b/storage.go @@ -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) + } } }