From f88ece46e3db6066a4239391a907d02bcce51d52 Mon Sep 17 00:00:00 2001 From: evilolipop Date: Wed, 6 Mar 2024 14:15:12 +0800 Subject: [PATCH] fix: fix nil option --- rotate.go | 10 ++++++---- rotate_file.go | 4 +++- rotate_file_test.go | 2 +- rotate_test.go | 17 +++++++++++++---- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/rotate.go b/rotate.go index ddea727..c650d2d 100644 --- a/rotate.go +++ b/rotate.go @@ -1,12 +1,14 @@ package logh import ( - "io" "log/slog" ) -func NewRotateJSONHandler(rollSize int, flushInterval int, opts *slog.HandlerOptions) (slog.Handler, error) { - var w io.Writer +func NewRotateJSONHandler(directory string, basename string, rollSize int, opts *slog.HandlerOptions, options ...Option) (slog.Handler, error) { + file, err := NewRotateFile(directory, basename, rollSize, options...) + if err != nil { + return nil, err + } - return slog.NewJSONHandler(w, opts), nil + return slog.NewJSONHandler(file, opts), nil } diff --git a/rotate_file.go b/rotate_file.go index 80436d7..efe474d 100644 --- a/rotate_file.go +++ b/rotate_file.go @@ -33,7 +33,9 @@ func NewRotateFile(directory string, basename string, rotateSize int, opts ...Op } for _, opt := range opts { - opt(rf) + if opt != nil { + opt(rf) + } } rf.rotate() diff --git a/rotate_file_test.go b/rotate_file_test.go index e29b5ce..2df7d25 100644 --- a/rotate_file_test.go +++ b/rotate_file_test.go @@ -14,7 +14,7 @@ func TestNewRotateFile(t *testing.T) { defer os.RemoveAll(path) path += "/TestNewRotateFile" - file, err := NewRotateFile(path, "test", 10) + file, err := NewRotateFile(path, "test", 10, nil) require.NoError(t, err) require.NotNil(t, file) diff --git a/rotate_test.go b/rotate_test.go index a918bdd..4aafbfc 100644 --- a/rotate_test.go +++ b/rotate_test.go @@ -1,7 +1,16 @@ package logh -// func TestRotateJSONHandler(t *testing.T) { -// handler, err := NewRotateJSONHandler(0, 0, nil) -// require.NoError(t, err) +import ( + "log/slog" + "testing" -// } + "github.com/stretchr/testify/require" +) + +func TestRotateJSONHandler(t *testing.T) { + handler, err := NewRotateJSONHandler("test", "test", 10, nil, nil) + require.NoError(t, err) + + logger := slog.New(handler) + logger.Info("test") +}