diff --git a/observability/log/log.go b/observability/log/log.go index 96a5347d2..84daca233 100644 --- a/observability/log/log.go +++ b/observability/log/log.go @@ -16,7 +16,21 @@ type Config struct { type ctxKey struct{} +var logCfg *Config + +// Setup sets up the logger with the given configuration. func Setup(cfg *Config) { + logCfg = cfg + setDefaultLogger(cfg) +} + +// SetLevel sets the logger level. +func SetLevel(lvl string) { + logCfg.Level = lvl + setDefaultLogger(logCfg) +} + +func setDefaultLogger(cfg *Config) { ho := &slog.HandlerOptions{ AddSource: true, Level: level(cfg.Level), @@ -30,7 +44,7 @@ func Setup(cfg *Config) { hnd = slog.NewTextHandler(os.Stderr, ho) } - slog.New(hnd.WithAttrs(cfg.Attributes)) + slog.SetDefault(slog.New(hnd.WithAttrs(cfg.Attributes))) } func level(lvl string) slog.Level { diff --git a/observability/log/log_test.go b/observability/log/log_test.go index c2544bddc..0fc1089b0 100644 --- a/observability/log/log_test.go +++ b/observability/log/log_test.go @@ -45,22 +45,19 @@ func TestContext(t *testing.T) { }) } -func TestEnabled(t *testing.T) { - type args struct { - l slog.Level - } - tests := map[string]struct { - args args - want bool - }{ - "Disabled": {args{slog.LevelDebug}, false}, - "Enabled": {args{slog.LevelInfo}, true}, - } - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - assert.Equal(t, tt.want, Enabled(tt.args.l)) - }) - } +func TestSetLevelAndCheckEnable(t *testing.T) { + Setup(&Config{ + Attributes: []slog.Attr{}, + IsJSON: true, + Level: "info", + }) + + assert.True(t, Enabled(slog.LevelInfo)) + assert.False(t, Enabled(slog.LevelDebug)) + + SetLevel("debug") + + assert.True(t, Enabled(slog.LevelDebug)) } func TestErrorAttr(t *testing.T) {