logger/slog: fixup race condition
Some checks failed
lint / lint (pull_request) Has been cancelled
pr / test (pull_request) Has been cancelled

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2024-02-22 08:57:21 +03:00
parent c2b97b0f20
commit 8e2eafde9c
2 changed files with 11 additions and 138 deletions

View File

@@ -7,6 +7,7 @@ import (
"os"
"runtime"
"strconv"
"sync"
"time"
"go.unistack.org/micro/v3/logger"
@@ -72,9 +73,11 @@ type slogLogger struct {
sourceKey string
timeKey string
opts logger.Options
mu sync.RWMutex
}
func (s *slogLogger) Clone(opts ...logger.Option) logger.Logger {
s.mu.RLock()
options := s.opts
for _, o := range opts {
@@ -112,6 +115,8 @@ func (s *slogLogger) Clone(opts ...logger.Option) logger.Logger {
handler := slog.NewJSONHandler(options.Out, handleOpt)
l.slog = slog.New(handler).With(options.Fields...)
s.mu.RUnlock()
return l
}
@@ -128,6 +133,7 @@ func (s *slogLogger) Options() logger.Options {
}
func (s *slogLogger) Fields(attrs ...interface{}) logger.Logger {
s.mu.RLock()
nl := &slogLogger{
opts: s.opts,
levelKey: s.levelKey,
@@ -147,10 +153,13 @@ func (s *slogLogger) Fields(attrs ...interface{}) logger.Logger {
handler := slog.NewJSONHandler(s.opts.Out, handleOpt)
nl.slog = slog.New(handler).With(attrs...)
s.mu.RUnlock()
return nl
}
func (s *slogLogger) Init(opts ...logger.Option) error {
s.mu.Lock()
for _, o := range opts {
o(&s.opts)
}
@@ -180,6 +189,8 @@ func (s *slogLogger) Init(opts ...logger.Option) error {
slog.SetDefault(s.slog)
s.mu.Unlock()
return nil
}