refactor(logging): move logging setup to internal/logging
Moves logging configuration and setup to a dedicated package. Updates Config struct to use nested LoggingConfig. Updates main.go to use the new logging package.
This commit is contained in:
37
internal/logging/logging.go
Normal file
37
internal/logging/logging.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Config holds the logging configuration.
|
||||
type Config struct {
|
||||
Level string `yaml:"level"`
|
||||
}
|
||||
|
||||
// Configure sets up the global logger based on the provided configuration.
|
||||
func Configure(cfg Config) *slog.Logger {
|
||||
opts := &slog.HandlerOptions{
|
||||
Level: parseLogLevel(cfg.Level),
|
||||
}
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
|
||||
slog.SetDefault(logger)
|
||||
return logger
|
||||
}
|
||||
|
||||
func parseLogLevel(level string) slog.Level {
|
||||
switch strings.ToLower(level) {
|
||||
case "debug":
|
||||
return slog.LevelDebug
|
||||
case "info":
|
||||
return slog.LevelInfo
|
||||
case "warn":
|
||||
return slog.LevelWarn
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
37
internal/logging/logging_test.go
Normal file
37
internal/logging/logging_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseLogLevel(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expected slog.Level
|
||||
}{
|
||||
{"debug", slog.LevelDebug},
|
||||
{"DEBUG", slog.LevelDebug},
|
||||
{"info", slog.LevelInfo},
|
||||
{"warn", slog.LevelWarn},
|
||||
{"error", slog.LevelError},
|
||||
{"unknown", slog.LevelInfo},
|
||||
{"", slog.LevelInfo},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
if got := parseLogLevel(tt.input); got != tt.expected {
|
||||
t.Errorf("parseLogLevel(%q) = %v, want %v", tt.input, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigure(t *testing.T) {
|
||||
cfg := Config{Level: "debug"}
|
||||
logger := Configure(cfg)
|
||||
if logger == nil {
|
||||
t.Error("Configure() returned nil")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user