How to test a specific log line is emitted in a function?

Could be useful when we expect a specific log line (usually a canonical log line) to be emitted when a specific function is called.

// We use a pipe, whose writer will be connected to the logger and we use the
//reader to check the content emitted by the logger. 
r, w, _ := os.Pipe()
 
// Set up the logger (usually the settings are done in a global manner to the singleton logger)
corelog.Init(corelog.WithOutput(w), ...)
// If you are using the golang standard log package, do:
// log.SetOutput(w)
 
// This scanner Go routine will keep scanning for texts from the reader of the
// pipe. It returns when the 'pipe' is closed.
wg := &sync.WaitGroup{}
ch := make(chan string)
wg.Add(1)
go func() {
  scanner := bufio.NewScanner(r)
  for scanner.Scan() {
    str := scanner.Text()
    // Use the following line for future debugging purposes
    // fmt.Fprintln(os.Stdout, "Scanned:", str)
    ch <- str
  }
  r.Close()
  wg.Done()
}()
 
// Call the function which contains logging lines.
testCase.f()
out := <-ch // this is result from scanner Go routine.
 
// Check the content of 'out'
assert.Contains(t, out, testCase.wantLines)
 
// Close the pipe and merge the thread of the scanner Go routine.
w.Close()
wg.Wait()