-1

I cannot get my program to write to the log file from a function outside of main() I did see https://stackoverflow.com/a/19966217/4374801 which is similar, but does not address my exact problem.
Here is the important bits of what I am doing:

var (
    Info    *log.Logger
    Error   *log.Logger
)

func init() {  
    // set up log file                                                                                                       
    fileHandle, err := os.OpenFile("/var/log/checkcert", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)                          
    if err != nil {                                                                                                          
        log.Fatal(err)                                                                                                       
    }                                                                                                                        
    //defer to close when you're done with it                                                                                
    defer fileHandle.Close()                                                                                                 

    //set output of logs to fileHandle                                                                                       
    log.SetOutput(fileHandle)                                                                                                

    Info = log.New(fileHandle,                                                                                               
        "Log: ",                                                                                                             
        log.Ldate|log.Ltime|log.Lshortfile)                                                                                  

    Error = log.New(fileHandle,                                                                                              
        "Error: ",                                                                                                           
        log.Ldate|log.Ltime|log.Lshortfile)                                                                                  
} 

// The function below is called from main()
// The version here is truncated to the pertinent bit
func checkDomain(){
    Info.Println("test inside checkDomain")
}

The above creates the log file, but does not write the test to it. If I put a test Println within init(), that works.

Roger Creasy
  • 1,419
  • 2
  • 19
  • 35

1 Answers1

2

The defer will execute at the end of the function, meaning your file will be closed at the end of the init function before you even run main. You should not close your file until main ends, so perhaps consider moving the initialisation of your loggers and file into the start of main instead of init.

darkliquid
  • 4,003
  • 1
  • 25
  • 17