CaptureOutput runs a function capturing its output at log level INFO.
(fun func())
| 11 | |
| 12 | // CaptureOutput runs a function capturing its output at log level INFO. |
| 13 | func CaptureOutput(fun func()) []byte { |
| 14 | var mu sync.Mutex |
| 15 | buf := &bytes.Buffer{} |
| 16 | oldLevel := log.Handler.SetLevel(slog.LevelInfo) |
| 17 | log.Handler.SetOutput(func(level slog.Level, text string) { |
| 18 | mu.Lock() |
| 19 | defer mu.Unlock() |
| 20 | buf.WriteString(text) |
| 21 | }) |
| 22 | defer func() { |
| 23 | log.Handler.ResetOutput() |
| 24 | log.Handler.SetLevel(oldLevel) |
| 25 | }() |
| 26 | fun() |
| 27 | mu.Lock() |
| 28 | defer mu.Unlock() |
| 29 | return buf.Bytes() |
| 30 | } |
searching dependent graphs…