1

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?

1
  • You shouldn't have a defer call at the end of the function. Are you exiting the test early in the // do stuff? Maybe post all your code to make things easier. Commented Jun 27, 2018 at 4:43

1 Answer 1

1

Try calling:

lf.Close()

before

os.Remove(logFile)

or you can replace

defer os.Remove(logFile)

with:

defer func() {
  lf.Close()
  os.Remove(logFile)
}()
Sign up to request clarification or add additional context in comments.

3 Comments

I see. hmm unfortunately the file was created in a function and lf is out of scope. It does explain why it's happening though.
I modified the function that sets logging to also return the *os.File handle. Then used your suggestion, but I had to reverse the order for the defer statements: defer os.Remove(logFile); defer lf.Close()
You have to close file handle before removing the file. The file will not really be deleted until the last handle is closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.