Skip to content

Commit

Permalink
feat: handle config
Browse files Browse the repository at this point in the history
  • Loading branch information
zstone12 committed Oct 28, 2024
1 parent e8e02f0 commit 99150d7
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions logging/slog/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,48 @@ func NewWriter(opts ...Option) *Writer {
for _, opt := range opts {
opt.apply(cfg)
}
// When user set the handlerOptions level but not set with coreconfig level
if !cfg.coreConfig.withLevel && cfg.coreConfig.withHandlerOptions && cfg.coreConfig.opt.Level != nil {
lvl := &slog.LevelVar{}
lvl.Set(cfg.coreConfig.opt.Level.Level())
cfg.coreConfig.level = lvl
}
cfg.coreConfig.opt.Level = cfg.coreConfig.level

var replaceAttrDefined bool
if cfg.coreConfig.opt.ReplaceAttr == nil {
replaceAttrDefined = false
} else {
replaceAttrDefined = true
}

replaceFunc := cfg.coreConfig.opt.ReplaceAttr

replaceAttr := func(groups []string, a slog.Attr) slog.Attr {
// default replaceAttr level
if a.Key == slog.LevelKey {
level := a.Value.Any().(slog.Level)
switch level {
case slog.LevelDebug:
a.Value = slog.StringValue("Debug")
case slog.LevelInfo:
a.Value = slog.StringValue("Info")
case slog.LevelWarn:
a.Value = slog.StringValue("Warn")
case slog.LevelError:
a.Value = slog.StringValue("Error")
default:
a.Value = slog.StringValue("Warn")
}
}
// append replaceAttr by user
if replaceAttrDefined {
return replaceFunc(groups, a)
} else {
return a
}
}
cfg.coreConfig.opt.ReplaceAttr = replaceAttr
logger := slog.New(NewTraceHandler(cfg.coreConfig.writer, cfg.coreConfig.opt, cfg.traceConfig))

return &Writer{log: logger, config: cfg}
Expand Down

0 comments on commit 99150d7

Please sign in to comment.