diff --git a/loggerx.go b/loggerx.go index 796a919..8455fd0 100644 --- a/loggerx.go +++ b/loggerx.go @@ -32,7 +32,7 @@ type filePath struct { fileName string } -func NewLogger(opts ...Option) *Logger { +func NewLogger(ctx context.Context, opts ...Option) *Logger { opt := defaultOptions() for _, apply := range opts { apply(&opt) @@ -61,6 +61,12 @@ func NewLogger(opts ...Option) *Logger { // 日志删除 go l.delete() + // 强制刷盘 + go func() { + <-ctx.Done() + l.MustSync() + }() + return l } diff --git a/loggerx_test.go b/loggerx_test.go index daf9fd2..a88380d 100644 --- a/loggerx_test.go +++ b/loggerx_test.go @@ -18,6 +18,7 @@ func TestLogger(t *testing.T) { b := bytes.NewBuffer(nil) l := loggerx.NewLogger( + context.Background(), loggerx.SetErrorToInfo(), loggerx.SetExtraDriver(b, Print{}), ) @@ -38,6 +39,6 @@ type Print struct { } func (pp Print) Write(p []byte) (n int, err error) { - fmt.Print("ppppppppppppppp",string(p)) + fmt.Print("ppppppppppppppp", string(p)) return } diff --git a/options.go b/options.go index 21ed8ec..288f8ac 100644 --- a/options.go +++ b/options.go @@ -16,6 +16,8 @@ type loggerOption struct { func defaultOptions() loggerOption { return loggerOption{ + isGinLog: true, + isGid: true, format: "json", dir: "./log", traceField: "trace_id", @@ -54,9 +56,9 @@ func SetFormat(format string) Option { } // 是否保存gin的日志 -func SetGinLog() Option { +func SetGinLog(open bool) Option { return func(o *loggerOption) { - o.isGinLog = true + o.isGinLog = open } } @@ -70,9 +72,9 @@ func SetDir(dir string) Option { } // 保存goroutine的ID信息 -func SetGID() Option { +func SetGID(open bool) Option { return func(o *loggerOption) { - o.isGid = true + o.isGid = open } }