Skip to content

Commit

Permalink
gcp: avoid type assertion panic (#29)
Browse files Browse the repository at this point in the history
Signed-off-by: Jason Hall <[email protected]>
  • Loading branch information
imjasonh authored Dec 30, 2024
1 parent 67ba3d0 commit 71baa29
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions gcp/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down
19 changes: 19 additions & 0 deletions gcp/setup_test.go
Original file line number Diff line number Diff line change
@@ -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")
}

0 comments on commit 71baa29

Please sign in to comment.