My code works in that it compiles, and when executed writes out a log file using a buffered writer.
But I wonder whether:
- I am correct in assuming that this actually winds up deferring a
.Close
that is always called - a package variable is the idiomatic way of doing this in Go
I realise that I could just have createLogger
return the file pointer, and defer on that ... but that seems even weirder, to have createLogger
set a package variable on log, then return the file pointer to be treated as a local ...
I'm still struggling with an idiom here.
package main
import (
"bufio"
"log"
"os"
)
var logFile *os.File
func main() {
createLogger()
defer logFile.Close()
// do some stuff
}
func createLogger() {
logFile, err := os.OpenFile("log/app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
os.Exit(-1)
}
log.SetOutput(bufio.NewWriter(logFile))
}