forked from baron/baron-sso
로그 포맷 통일, slog 적용
This commit is contained in:
49
backend/internal/logger/logger.go
Normal file
49
backend/internal/logger/logger.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Config holds the logger configuration
|
||||
type Config struct {
|
||||
ServiceName string
|
||||
Environment string // "dev", "local", "production"
|
||||
}
|
||||
|
||||
// Init initializes the global logger with slog.
|
||||
// It detects the environment to switch between TextHandler (dev) and JSONHandler (prod).
|
||||
func Init(cfg Config) {
|
||||
var handler slog.Handler
|
||||
|
||||
opts := &slog.HandlerOptions{
|
||||
// Default level
|
||||
Level: slog.LevelInfo,
|
||||
// Customize attributes (Time format)
|
||||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
return slog.String(a.Key, a.Value.Time().Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
return a
|
||||
},
|
||||
}
|
||||
|
||||
// Adjust level and format based on environment
|
||||
env := strings.ToLower(cfg.Environment)
|
||||
if env == "dev" || env == "local" || env == "development" {
|
||||
opts.Level = slog.LevelDebug
|
||||
handler = slog.NewTextHandler(os.Stdout, opts)
|
||||
} else {
|
||||
// Production defaults to JSON
|
||||
handler = slog.NewJSONHandler(os.Stdout, opts)
|
||||
}
|
||||
|
||||
// Create logger with common attributes
|
||||
logger := slog.New(handler).With(
|
||||
slog.String("svc", cfg.ServiceName),
|
||||
)
|
||||
|
||||
// Set as global default logger
|
||||
slog.SetDefault(logger)
|
||||
}
|
||||
Reference in New Issue
Block a user