2

I have the following code:

func main() {
    initSetLogOutput()

    log.Println("Another log")
}

func initSetLogOutput() {
    f, err := os.OpenFile("errors.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)
    log.Println("This is a test log entry")
}

After compilation I run the application and I get the the first log This is a test log entry but the second log does not write to the log file. What is causing this? Is the declaration of log.SetOutput limited to the scope of a function? How do I get the log output option to persist throughout the entire application?

My output log looks like below:

2019/01/10 15:53:36 This is a test log entry
2019/01/10 15:54:27 This is a test log entry
2019/01/10 15:55:43 This is a test log entry
2019/01/10 15:57:40 This is a test log entry
2019/01/10 16:02:27 This is a test log entry
2
  • Your initSetLogOutput closes f on return (defer f.Close()), so once it returns and main resumes, the file pointer is closed and the logger has nowhere to write to. Commented Jan 10, 2019 at 16:07
  • Ok, I had wondered if that was the cause, but I wasn't sure what would be best practice. So I should write some code close the file when the application closes. Commented Jan 10, 2019 at 16:08

1 Answer 1

5

Inside initSetLogOutput() you have a defer f.Close() line, which means before initSetLogOutput() returns, the file will be closed.

Instead close it at the end of main(), like this:

func main() {
    initSetLogOutput()
    log.Println("Another log")
    closeLogOutput()
}

var logFile *os.File

func initSetLogOutput() {
    var err error
    logFile, err = os.OpenFile("errors.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }

    log.SetOutput(logFile)
    log.Println("This is a test log entry")
}

func closeLogOutput() {
    logFile.Close()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me better understand the way golang's process flow works

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.