简体   繁体   中英

Write log by Golang logger

I am trying to write log by using log.Logger , my code is like bellow. I don't understand why my log can be written using Error inside initLog function but in main function it can't be written to the log file.
Can anybody explain for me?
Thanks.

package main

import (
    "log"
    "net/http"
    "os"
)

const (
    PORT = ":8081"
)

var (
    Error *log.Logger
)

func initLog() {
    errorFile, err := os.OpenFile("error.log", os.O_RDWR|os.O_APPEND, 0660)
    defer errorFile.Close()

    if err != nil {
        log.Fatal(err)
    }

    Error = log.New(errorFile, "ERROR: ", log.Ldate|log.Ltime)
    Error.SetOutput(errorFile)
    Error.Println("Log error will be written into error.log")

}

func main() {
    initLog()
    Error.Println("Test write log")
    http.ListenAndServe(PORT, http.FileServer(http.Dir('.')))
}

You're closing the file when returning from initLog() using defer errorFile.Close() so inside main() the file errorFile is closed.

So comment this line:

defer errorFile.Close()

And move it to the main() .

You're calling defer errorFile.Close() in initLog() . As soon as initLog() returns the defer is executed and because of this, when Error.Println("Test write log") is called in your main, the io.Writer is already closed.

Also you should check for errors first and then call defer <what ever you need to do> like

errorFile, err := os.OpenFile("error.log", os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
    log.Fatal(err)
}
defer errorFile.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM