mirror of
https://github.com/rclone/rclone.git
synced 2025-12-06 00:03:32 +00:00
Before this change CaptureOutput could trip the race detector when used concurrently. In particular if go routines using the logging are outlasting the return from `fun()`. This fixes the problem with a mutex.
31 lines
626 B
Go
31 lines
626 B
Go
// Package bilib provides common stuff for bisync and bisync_test
|
|
package bilib
|
|
|
|
import (
|
|
"bytes"
|
|
"log/slog"
|
|
"sync"
|
|
|
|
"github.com/rclone/rclone/fs/log"
|
|
)
|
|
|
|
// CaptureOutput runs a function capturing its output at log level INFO.
|
|
func CaptureOutput(fun func()) []byte {
|
|
var mu sync.Mutex
|
|
buf := &bytes.Buffer{}
|
|
oldLevel := log.Handler.SetLevel(slog.LevelInfo)
|
|
log.Handler.SetOutput(func(level slog.Level, text string) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
buf.WriteString(text)
|
|
})
|
|
defer func() {
|
|
log.Handler.ResetOutput()
|
|
log.Handler.SetLevel(oldLevel)
|
|
}()
|
|
fun()
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
return buf.Bytes()
|
|
}
|