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
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()
}