通过Golang记录器写日志
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('.')))
}
我正在尝试使用 log.Logger code>编写日志,我的代码就像下面这样 。 我不明白为什么可以在
initLog code>函数中使用Error写入我的日志,但是在
main code>函数中却无法将其写入日志文件。
Can 有人帮我解释一下吗?
谢谢。 p>
程序包main
import(
“ log”
“ net / http”
“ os” \ n)
const(
PORT =“:8081”
)
var(
错误* log.Logger
)
func initLog(){
errorFile,err:= os。 OpenFile(“ error.log”,os.O_RDWR | os.O_APPEND,0660)
延迟errorFile.Close()
如果错误!= nil {
log.Fatal(err)
}
\ n错误= log.New(errorFile,“ ERROR:”,log.Ldate | log.Ltime)
Error.SetOutput(errorFile)
Error.Println(“日志错误将被写入error.log”)
}
func main(){
initLog()
Error.Println(“ Test write log”)
http.ListenAndServe(PORT,http.FileServer(http.Dir('。')))
}
code> pre>
div>
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()