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

Am trying to create a logger which outputs to a file instead of the stdout. I instantiated the logger in the init function but it doesn’t work out of the init func, like i can’t write logs anymore if am doing it out of the init function.
Here is a sample of the code

var logger *log.Logger

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

	defer logFile.Close()

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

Then if i try to invoke the logger in another function, it just doesn’t work!!

func handlePanic() {
	if message := recover(); message != nil {
		logger.Fatalln("Panic occurred:", message)
	}
}

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.