From 71baa290ade35c2c17bfaf3de9abd8eff386b3f6 Mon Sep 17 00:00:00 2001 From: Jason Hall Date: Mon, 30 Dec 2024 14:24:43 -0500 Subject: [PATCH] gcp: avoid type assertion panic (#29) Signed-off-by: Jason Hall --- gcp/setup.go | 4 ++-- gcp/setup_test.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 gcp/setup_test.go diff --git a/gcp/setup.go b/gcp/setup.go index 2ec97fa..fed168d 100644 --- a/gcp/setup.go +++ b/gcp/setup.go @@ -26,8 +26,8 @@ func NewHandler(level slog.Level) *Handler { a.Key = "logging.googleapis.com/sourceLocation" } else if a.Key == slog.LevelKey { a.Key = "severity" - level := a.Value.Any().(slog.Level) - if level == LevelCritical { + level, ok := a.Value.Any().(slog.Level) + if ok && level == LevelCritical { a.Value = slog.StringValue("CRITICAL") } } diff --git a/gcp/setup_test.go b/gcp/setup_test.go new file mode 100644 index 0000000..13bc970 --- /dev/null +++ b/gcp/setup_test.go @@ -0,0 +1,19 @@ +package gcp + +import ( + "context" + "log/slog" + "testing" +) + +func TestHandler(t *testing.T) { + ctx := context.Background() + l := slog.New(NewHandler(slog.LevelInfo)) + l.With("level", "INFO").Log(ctx, slog.LevelInfo, "hello world") // okay + l.With("level", "INFO").Log(ctx, slog.LevelWarn, "hello world") // weird, but okay (info) + + // These should not panic. + l.With("level", nil).Log(ctx, slog.LevelInfo, "hello world") + l.With("level", 123).Log(ctx, slog.LevelInfo, "hello world") + l.With("level", map[string]string{}).Log(ctx, slog.LevelInfo, "hello world") +}