去测试删除logger.SetLogging日志文件

I have a TestCase for a function that defines a log file path, then sets logger, so that log.* statements are written to standard out and the log file:

lf, err := os.Create(logFile)
mw := io.MultiWriter(os.Stdout, lf)
log.SetOutput(mw)

In my Test case I'm attempting to cleanup at the end, but it appears there is a lock on the file still, which means the Os.Remove() call is not working (or even returning an error)

I've tried to SetOutput to nil as well as using a defer statement.

func TestSetLogging(t *testing.T) {
// do stuff
...
log.Println("this should be in logger file")

// cleanup
log.SetOutput(nil)
defer os.Remove(logFile)
}

Yet, the logFile still appears on disk. How can I delete this file?

Try calling:

lf.Close()

before

os.Remove(logFile)

or you can replace

defer os.Remove(logFile)

with:

defer func() {
  lf.Close()
  os.Remove(logFile)
}()