golang提供了一個(gè)簡單的日志輸出包log迄汛,常用用法,已經(jīng)基本滿足日常的日志輸出需求
1骤视、日志級別有3個(gè)鞍爱,info,fatal,panic
2专酗、 日志文件的輸出
import (
"log"
"os"
)
func main() {
logFile,err:=os.Create("./log.log")
defer logFile.Close()
if err !=nil{
log.Fatalln("create file log.log failed")
}
logger:=log.New(logFile,"[Debug]",log.Lshortfile)
logger.Println("debug info is ,check list ,hello")
logger.Println("debug info is ,check list ,hello000111")
logger.SetPrefix("[Info]")
logger.SetFlags(log.Ldate)
logger.SetOutput(logFile)
logger.Print("Info check")
logger.SetOutput(os.Stdout)
logger.Print("Info check stdout")
}
輸出的結(jié)果 a.log
[Debug]main.go:45: debug info is ,check list ,hello
[Debug]main.go:46: debug info is ,check list ,hello000111
[Info]2020/09/09 Info check
標(biāo)準(zhǔn)輸出:
[Info]2020/09/09 Info check stdout
樣例二:
package main
import (
"example/ch07/apps"
"example/ch07/utils"
"log"
"os"
)
func main() {
logFile,err:=os.OpenFile("./log.log",os.O_WRONLY | os.O_CREATE | os.O_APPEND,0664)
defer logFile.Close()
if err !=nil{
log.Fatalln("create file log.log failed")
}
utils.Init(logFile)
log.Print("Check init info")
apps.Check()
}
package utils
import (
"io"
"log"
)
func Init(logFile io.Writer){
log.SetOutput(logFile)
log.SetPrefix("[Info]")
log.SetFlags(log.Ldate)
}
package apps
import "log"
func Check(){
log.Println("go to function Check")
}
輸出結(jié)果為:
[Info]2020/09/09 Check init info
[Info]2020/09/09 go to function Check