From 203b084e17faafc9415cc3c337ad1eff738cb4a1 Mon Sep 17 00:00:00 2001 From: Maksim Nabokikh Date: Mon, 3 Jun 2024 23:23:14 +0400 Subject: [PATCH] Fix slog nil pointer error (#3563) The problem caused by the mistake in the newLogger function. The nil value is returned even with the valid log format. Signed-off-by: m.nabokikh --- cmd/dex/serve.go | 4 ++-- cmd/dex/serve_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 cmd/dex/serve_test.go diff --git a/cmd/dex/serve.go b/cmd/dex/serve.go index b39354ec0b..456e07f6a9 100644 --- a/cmd/dex/serve.go +++ b/cmd/dex/serve.go @@ -520,11 +520,11 @@ func newLogger(level slog.Level, format string) (*slog.Logger, error) { var handler slog.Handler switch strings.ToLower(format) { case "", "text": - slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + handler = slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: level, }) case "json": - slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ + handler = slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ Level: level, }) default: diff --git a/cmd/dex/serve_test.go b/cmd/dex/serve_test.go new file mode 100644 index 0000000000..9e214480d3 --- /dev/null +++ b/cmd/dex/serve_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "log/slog" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNewLogger(t *testing.T) { + t.Run("JSON", func(t *testing.T) { + logger, err := newLogger(slog.LevelInfo, "json") + require.NoError(t, err) + require.NotEqual(t, (*slog.Logger)(nil), logger) + }) + + t.Run("Text", func(t *testing.T) { + logger, err := newLogger(slog.LevelError, "text") + require.NoError(t, err) + require.NotEqual(t, (*slog.Logger)(nil), logger) + }) + + t.Run("Unknown", func(t *testing.T) { + logger, err := newLogger(slog.LevelError, "gofmt") + require.Error(t, err) + require.Equal(t, "log format is not one of the supported values (json, text): gofmt", err.Error()) + require.Equal(t, (*slog.Logger)(nil), logger) + }) +}