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)
} else if logFile != "" {
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
}
output = io.MultiWriter(logOutputF, terminalOutput)
output = io.MultiWriter(logOutputFile, terminalOutput)
context = append(context, "location", logFile)
} else {
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"
if useColor {
terminalOutput = colorable.NewColorableStderr()
if logOutputF != nil {
output = io.MultiWriter(logOutputF, terminalOutput)
if logOutputFile != nil {
output = io.MultiWriter(logOutputFile, terminalOutput)
} else {
output = terminalOutput
}
@ -337,8 +337,8 @@ func StartPProf(address string, withMetrics bool) {
func Exit() {
Handler.StopCPUProfile()
Handler.StopGoTrace()
if logOutputF != nil {
logOutputF.Close()
if logOutputFile != nil {
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 {
h.lock.RLock()
siteCache := make(map[uintptr]slog.Level)
for k, v := range h.siteCache {
siteCache[k] = v
}
h.lock.RUnlock()
res := GlogHandler{
h.origin.WithAttrs(attrs),
atomic.Int32{},
atomic.Bool{},
h.patterns,
h.siteCache,
h.location,
sync.RWMutex{},
origin: h.origin.WithAttrs(attrs),
patterns: h.patterns,
siteCache: siteCache,
location: h.location,
}
res.level.Store(h.level.Load())

View file

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