log: copy siteCache map when instantiating GlogHandler via WithAttrs method

This commit is contained in:
Jared Wasinger 2023-11-15 16:22:17 +08:00
parent 813b1e9c54
commit e25cb5ce80
3 changed files with 17 additions and 17 deletions

View file

@ -228,10 +228,10 @@ func Setup(ctx *cli.Context) error {
output = io.MultiWriter(terminalOutput, logOutputFile) output = io.MultiWriter(terminalOutput, logOutputFile)
} else if logFile != "" { } else if logFile != "" {
var err error var err error
if logOutputF, err = os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err != nil { if logOutputFile, err = os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err != nil {
return err return err
} }
output = io.MultiWriter(logOutputF, terminalOutput) output = io.MultiWriter(logOutputFile, terminalOutput)
context = append(context, "location", logFile) context = append(context, "location", logFile)
} else { } else {
output = terminalOutput output = terminalOutput
@ -250,8 +250,8 @@ func Setup(ctx *cli.Context) error {
useColor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb" useColor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
if useColor { if useColor {
terminalOutput = colorable.NewColorableStderr() terminalOutput = colorable.NewColorableStderr()
if logOutputF != nil { if logOutputFile != nil {
output = io.MultiWriter(logOutputF, terminalOutput) output = io.MultiWriter(logOutputFile, terminalOutput)
} else { } else {
output = terminalOutput output = terminalOutput
} }
@ -337,8 +337,8 @@ func StartPProf(address string, withMetrics bool) {
func Exit() { func Exit() {
Handler.StopCPUProfile() Handler.StopCPUProfile()
Handler.StopGoTrace() Handler.StopGoTrace()
if logOutputF != nil { if logOutputFile != nil {
logOutputF.Close() logOutputFile.Close()
} }
} }

View file

@ -145,14 +145,18 @@ func (h *GlogHandler) Enabled(ctx context.Context, lvl slog.Level) bool {
} }
func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
h.lock.RLock()
siteCache := make(map[uintptr]slog.Level)
for k, v := range h.siteCache {
siteCache[k] = v
}
h.lock.RUnlock()
res := GlogHandler{ res := GlogHandler{
h.origin.WithAttrs(attrs), origin: h.origin.WithAttrs(attrs),
atomic.Int32{}, patterns: h.patterns,
atomic.Bool{}, siteCache: siteCache,
h.patterns, location: h.location,
h.siteCache,
h.location,
sync.RWMutex{},
} }
res.level.Store(h.level.Load()) res.level.Store(h.level.Load())

View file

@ -51,7 +51,3 @@ func BenchmarkTraceLogging(b *testing.B) {
Trace("a message", "v", i) Trace("a message", "v", i)
} }
} }
func TestLoggingWithAttrs(t *testing.T) {
// TODO: test logger.With(...)
}