Golang *Logger Blocking the Async Go-Routine Call

My error log function is like this, returning *logger as return.

func StartLogs(logFile string) *log.Logger {
// open file and create if non-existent
file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
logger := log.New(file, “Custom Log”, log.LstdFlags)
return logger
}

I am using it like this.
myLogger:=StartLogs(‘logfile.log’)

go DoSomething(user.Filename, myLogger)

Now *logger will not allow go-routine to run asynchronously.
What would be the way to perform this action?

Hi, @Arshpreet_Singh, welcome to the forum. I’m not exactly sure what you mean about the goroutine not being able to run asynchronously, but I see a potential issue with your StartLogs function: It defers closing the log file. This means that when the logger is returned to the caller of StartLogs, the logger’s destination file is closed, and I’m not sure what will happen when an attempt is made to write a log message after that. I recommend changing your StartLogs function to something similar to this:

func StartLogs(logFile strinf) (logger *log.Logger, closer func() error) {
    // existing code here, but don't defer closing the file
    return logger, f.Close
}

Then you can defer calling close on the closer function where you call StartLogs:

logger, closer := StartLogs(logFilename)
defer closer()
// use logger