Why does initiating a logger in init function not working outside the init func?

I found the reason why the logger wasn’t writing anything to the log file. It’s because the file would be closed when the init function ends thus preventing the logger from writing to it. The solution i found is to make the file a package level variable then move the file.Close() call inside the main function so that the file gets closed when the program exits.

var (
	logger  *log.Logger
	logFile *os.File
)

func init() {

	logFile, err := os.OpenFile("app-log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)

	if err != nil {
		fmt.Println("Failed to create the log file")
		fmt.Println(err)
		os.Exit(1)
	}

	logger = log.New(logFile, "log-prefix-here:", log.Ldate)
}

func main() {
	defer logFile.Close()
...
1 Like