logger/slog: add option to pass slog.Handler
All checks were successful
test / test (push) Successful in 45s

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2024-12-07 14:18:25 +03:00
parent 9213fd212f
commit 0e66688f8f
2 changed files with 20 additions and 2 deletions

View File

@ -171,7 +171,19 @@ func (s *slogLogger) Init(opts ...logger.Option) error {
}
attrs, _ := s.argsAttrs(s.opts.Fields)
s.handler = &wrapper{h: slog.NewJSONHandler(s.opts.Out, handleOpt).WithAttrs(attrs)}
var h slog.Handler
if s.opts.Context != nil {
if v, ok := s.opts.Context.Value(handlerKey{}).(slog.Handler); ok && v != nil {
h = v
}
}
if h == nil {
h = slog.NewJSONHandler(s.opts.Out, handleOpt)
}
s.handler = &wrapper{h: h.WithAttrs(attrs)}
s.handler.level.Store(int64(loggerToSlogLevel(s.opts.Level)))
s.mu.Unlock()
@ -329,3 +341,9 @@ func (s *slogLogger) argsAttrs(args []interface{}) ([]slog.Attr, error) {
return attrs, err
}
type handlerKey struct{}
func WithHandler(h slog.Handler) logger.Option {
return logger.SetOption(handlerKey{}, h)
}

View File

@ -10,7 +10,7 @@ import (
var (
ErrWatcherStopped = errors.New("watcher stopped")
// ErrNotConnected is returned when a store is not connected
ErrNotConnected = errors.New("not conected")
ErrNotConnected = errors.New("not connected")
// ErrNotFound is returned when a key doesn't exist
ErrNotFound = errors.New("not found")
// ErrInvalidKey is returned when a key has empty or have invalid format