From d4c612f52d2066a879c1861702700d105bb9438b Mon Sep 17 00:00:00 2001 From: Jeffry Luqman Date: Mon, 25 Sep 2023 12:55:16 +0700 Subject: [PATCH] custom writer --- zlog.go | 12 ++++++------ zlog_test.go | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/zlog.go b/zlog.go index 4032f64..29257ee 100644 --- a/zlog.go +++ b/zlog.go @@ -71,17 +71,17 @@ var ( ) var ( - w io.Writer - log *slog.Logger + Writer io.Writer + log *slog.Logger ) // New creates a new logger instance and returns it. func New() *slog.Logger { - if w == nil { - w = colorable.NewColorableStdout() + if Writer == nil { + Writer = colorable.NewColorableStdout() } if log == nil { - log = slog.New(&logHandler{sh: slog.NewTextHandler(w, HandlerOptions)}) + log = slog.New(&logHandler{sh: slog.NewTextHandler(Writer, HandlerOptions)}) } return log } @@ -193,7 +193,7 @@ func (h *logHandler) Handle(ctx context.Context, r slog.Record) error { h.write(b, Fmt(a.Key, FmtAttrKey...), Fmt(KeyDelimiter, FmtAttrDelimiter...), Fmt(a.Value.String(), FmtAttrValue...), " ") } h.write(b, "\n") - _, err := b.WriteTo(w) + _, err := b.WriteTo(Writer) return err } func (h *logHandler) write(b *bytes.Buffer, args ...string) { diff --git a/zlog_test.go b/zlog_test.go index e60d047..e190a8c 100644 --- a/zlog_test.go +++ b/zlog_test.go @@ -12,14 +12,14 @@ import ( // This code is modified from https://github.com/golang/go/blob/54f78cf8f1b8deea787803aeff5fb6150d7fac8f/src/log/slog/logger_test.go#L27 func TestZlog(t *testing.T) { ctx := context.Background() - w = &bytes.Buffer{} + Writer = &bytes.Buffer{} TimeFormat = "Z" l := New() check := func(want []byte) { t.Helper() - x, ok := w.(*bytes.Buffer) + x, ok := Writer.(*bytes.Buffer) if ok { t.Helper() got := x.Bytes() @@ -106,7 +106,7 @@ func BenchmarkSlog(b *testing.B) { // This is a simple benchmark. See the benchmarks subdirectory for more extensive ones. // This code is modified from https://github.com/golang/go/blob/54f78cf8f1b8deea787803aeff5fb6150d7fac8f/src/log/slog/logger_test.go#L522 func BenchmarkZlog(b *testing.B) { - w = io.Discard + Writer = io.Discard ctx := context.Background() l := New() b.Run("no attrs", func(b *testing.B) {