golang提供了一个简单的日志输出包log,常用用法,已经基本满足日常的日志输出需求
1、日志级别有3个,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")
}
输出的结果 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
标准输出:
[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")
}
输出结果为:
[Info]2020/09/09 Check init info
[Info]2020/09/09 go to function Check
有疑问加站长微信联系(非本文作者)