Skip to content

Commit

Permalink
custom writer
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffry-luqman committed Sep 25, 2023
1 parent 5424e4c commit d4c612f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
12 changes: 6 additions & 6 deletions zlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions zlog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit d4c612f

Please sign in to comment.