Skip to content

Commit

Permalink
Logging refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
mantzas committed Oct 24, 2024
1 parent 1578b27 commit d86e1d5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
16 changes: 15 additions & 1 deletion observability/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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 {
Expand Down
29 changes: 13 additions & 16 deletions observability/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit d86e1d5

Please sign in to comment.