From c7acaa5af6b1dbf9d631f741c9dae4dc729bafa1 Mon Sep 17 00:00:00 2001 From: Yun Date: Mon, 15 Apr 2024 23:26:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=94=AF=E6=8C=81=E6=9B=B4?= =?UTF-8?q?=E5=A4=9A=E7=9A=84=E6=96=87=E4=BB=B6=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- loggerx_test.go | 19 ++++++++++++++++++- options.go | 23 ++++++++++++++++++++--- storage.go | 3 ++- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/loggerx_test.go b/loggerx_test.go index e6c1795..daf9fd2 100644 --- a/loggerx_test.go +++ b/loggerx_test.go @@ -1,7 +1,9 @@ package loggerx_test import ( + "bytes" "context" + "fmt" "testing" "time" @@ -13,7 +15,12 @@ import ( func TestLogger(t *testing.T) { - l := loggerx.NewLogger(loggerx.SetErrorToInfo()) + b := bytes.NewBuffer(nil) + + l := loggerx.NewLogger( + loggerx.SetErrorToInfo(), + loggerx.SetExtraDriver(b, Print{}), + ) l.Error(context.Background(), "test error") @@ -22,5 +29,15 @@ func TestLogger(t *testing.T) { l.Info(context.Background(), "test info") + fmt.Println(b.String()) + time.Sleep(time.Second * 5) } + +type Print struct { +} + +func (pp Print) Write(p []byte) (n int, err error) { + fmt.Print("ppppppppppppppp",string(p)) + return +} diff --git a/options.go b/options.go index eb46435..21ed8ec 100644 --- a/options.go +++ b/options.go @@ -1,14 +1,17 @@ package loggerx +import "io" + type loggerOption struct { prefix string // 日志前缀 format string // text json dir string // 文件目录 isGinLog bool isGid bool - traceField string // trace字段 - errorToInfo bool // 错误日志是否写入info日志 - days int // 日志保存天数 + traceField string // trace字段 + errorToInfo bool // 错误日志是否写入info日志 + days int // 日志保存天数 + drivers []io.Writer // 文件落盘驱动器 } func defaultOptions() loggerOption { @@ -80,6 +83,20 @@ func SetDays(days int) Option { } } +// 设置时区 +func SetTimeZone() Option { + return func(o *loggerOption) { + // o.timeZone = timeZone + } +} + +// 文件额外的驱动 +func SetExtraDriver(ds ...io.Writer) Option { + return func(o *loggerOption) { + o.drivers = ds + } +} + // 文件切割规则 // 1.文件大小 // 2.时间A(年/月/日/时) diff --git a/storage.go b/storage.go index 9f97c3d..b44359f 100644 --- a/storage.go +++ b/storage.go @@ -18,5 +18,6 @@ func (l *Logger) write(event string, b []byte) (n int, err error) { // 强制更新 l.getFile(event, true) } - return f.Write(b) + d := append(l.option.drivers, f) + return io.MultiWriter(d...).Write(b) }