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('.')))
}