Go標(biāo)準(zhǔn)庫(kù)日志打印及同時(shí)輸出到控制臺(tái)與文件
打印
在使用go寫(xiě)一些小程序時(shí),我們沒(méi)必要引入額外的包,直接使用fmt標(biāo)準(zhǔn)包打印即可:
import "fmt"
func main() {
fmt.Println("line1")
fmt.Print("line2")
fmt.Printf("line%d \n", 3)
str1 := fmt.Sprintln("hello", 3)
str2 := fmt.Sprint("hello ", 1, " 2")
str3 := fmt.Sprintf("hello %d", 1)
fmt.Print(str1, str2, str3)
}
line1
line2line3
hello 3
hello 1 2hello 1
那么,有些場(chǎng)景下,我們希望能同時(shí)打印到日志文件中要怎么辦呢?
log包
標(biāo)準(zhǔn)庫(kù)提供了log組件,用法和fmt一致,有3種方式:
import “l(fā)og"
func main() {
log.Println("line1")
log.Print("line2")
log.Printf("line%d \n", 3)
}
和fmt的區(qū)別就是多了時(shí)間:
2021/08/25 17:23:47 line1
2021/08/25 17:23:47 line2
2021/08/25 17:23:47 line3
我們通過(guò)SetFlag函數(shù),可以設(shè)置打印的格式:
// For example, flags Ldate | Ltime (or LstdFlags) produce, // 2009/01/23 01:23:23 message // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce, // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message const ( Ldate = 1 << iota // the date in the local time zone: 2009/01/23 Ltime // the time in the local time zone: 01:23:23 Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime. Llongfile // full file name and line number: /a/b/c/d.go:23 Lshortfile // final file name element and line number: d.go:23. overrides Llongfile LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone Lmsgprefix // move the "prefix" from the beginning of the line to before the message LstdFlags = Ldate | Ltime // initial values for the standard logger )
比如,我們只需要時(shí)間和文件名:
import “l(fā)og"
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("line1")
log.Print("line2")
log.Printf("line%d \n", 3)
}
此時(shí),再次運(yùn)行,則會(huì)打印文件和行號(hào):
2021/08/25 17:27:56 mod_unread_redis.go:32: line1
2021/08/25 17:27:56 mod_unread_redis.go:33: line2
2021/08/25 17:27:56 mod_unread_redis.go:34: line3
如何輸出日志到文件?
log包使用非常簡(jiǎn)單,默認(rèn)情況下,只會(huì)輸出到控制臺(tái)。
我們可以使用SetOutput改變輸出流,比如輸出到文件。
先來(lái)看一下函數(shù)原型,其接收一個(gè)io.Writer接口:
// SetOutput sets the output destination for the standard logger.
func SetOutput(w io.Writer) {
// ...
}
那么,我們就可以創(chuàng)建一個(gè)文件流設(shè)置一下就行了。
// 創(chuàng)建、追加、讀寫(xiě),777,所有權(quán)限
f, err := os.OpenFile("log.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
if err != nil {
return
}
defer func() {
f.Close()
}()
log.SetOutput(f)
此時(shí),在運(yùn)行,我們發(fā)現(xiàn)日志會(huì)輸出到文件,但是控制臺(tái)沒(méi)有任何東西輸出了。
如何同時(shí)輸出到控制臺(tái)和文件?
標(biāo)準(zhǔn)庫(kù)io包中,有一個(gè)MultiWriter,可以把文件流和控制臺(tái)標(biāo)準(zhǔn)輸出流整合到一個(gè)io.Writer上,其實(shí)現(xiàn)上就是一個(gè)數(shù)組,在執(zhí)行寫(xiě)操作時(shí),遍歷數(shù)組:
// MultiWriter creates a writer that duplicates its writes to all the
// provided writers, similar to the Unix tee(1) command.
//
// Each write is written to each listed writer, one at a time.
// If a listed writer returns an error, that overall write operation
// stops and returns the error; it does not continue down the list.
func MultiWriter(writers ...Writer) Writer {
allWriters := make([]Writer, 0, len(writers))
for _, w := range writers {
if mw, ok := w.(*multiWriter); ok {
allWriters = append(allWriters, mw.writers...)
} else {
allWriters = append(allWriters, w)
}
}
return &multiWriter{allWriters}
}
// 重寫(xiě)io.Writer的Write函數(shù)函數(shù),本質(zhì)上就是遍歷數(shù)組,比較巧妙
func (t *multiWriter) Write(p []byte) (n int, err error) {
for _, w := range t.writers {
n, err = w.Write(p)
if err != nil {
return
}
if n != len(p) {
err = ErrShortWrite
return
}
}
return len(p), nil
}
使用方式如下:
func main() {
f, err := os.OpenFile("log.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
if err != nil {
return
}
defer func() {
f.Close()
}()
// 組合一下即可,os.Stdout代表標(biāo)準(zhǔn)輸出流
multiWriter := io.MultiWriter(os.Stdout, f)
log.SetOutput(multiWriter)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("line1")
log.Print("line2")
log.Printf("line%d \n", 3)
}
此時(shí),再運(yùn)行,則會(huì)同時(shí)輸出到控制臺(tái)和文件中。
2021/08/25 17:38:02 mod_unread_redis.go:42: line1
2021/08/25 17:38:02 mod_unread_redis.go:43: line2
2021/08/25 17:38:02 mod_unread_redis.go:44: line3

附:日志切割(按文件大小切割、按日期切割)
其實(shí)就是每次記錄文件的大小,超過(guò)了就重新寫(xiě)一個(gè)文件。
通過(guò)Stat()函數(shù)拿到文件的一些信息
open, _:= os.Open("文件名")
stat, _, := open.Stat()
stat.Size()//拿到文件大小
日期切割:
拿到文件的名稱(chēng)或者檢查下有沒(méi)有當(dāng)天的日志文件,沒(méi)有就創(chuàng)建新增。
總結(jié)
到此這篇關(guān)于Go標(biāo)準(zhǔn)庫(kù)日志打印及同時(shí)輸出到控制臺(tái)與文件的文章就介紹到這了,更多相關(guān)Go標(biāo)準(zhǔn)庫(kù)日志打印及輸出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang中sync.Mutex的實(shí)現(xiàn)方法
本文主要介紹了golang中sync.Mutex的實(shí)現(xiàn)方法,mutex?主要有兩個(gè)?method:?Lock()?和?Unlock(),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
GO語(yǔ)言實(shí)現(xiàn)TCP服務(wù)器的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何通過(guò)GO語(yǔ)言實(shí)現(xiàn)TCP服務(wù)器,文中的示例代碼講解詳細(xì),對(duì)我們深入了解Go語(yǔ)言有一定的幫助,需要的可以參考一下2023-03-03
Go語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單留言板的方法
這篇文章主要介紹了Go語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單留言板的方法,涉及數(shù)據(jù)庫(kù)、模板頁(yè)面元素等留言板相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02
Go語(yǔ)言開(kāi)發(fā)k8s之Deployment操作解析
這篇文章主要為大家介紹了Go語(yǔ)言開(kāi)發(fā)k8s之Deployment操作解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
解析Golang中引用類(lèi)型是否進(jìn)行引用傳遞
這篇文章主要為大家介紹了Golang中引用類(lèi)型是否進(jìn)行引用傳遞剖析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Go語(yǔ)言下載網(wǎng)絡(luò)圖片或文件的方法示例
這篇文章主要介紹了Go語(yǔ)言下載網(wǎng)絡(luò)圖片或文件的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
Golang實(shí)現(xiàn)WebSocket服務(wù)的項(xiàng)目實(shí)踐
本文介紹如何使用Golang實(shí)現(xiàn)實(shí)時(shí)后端WebSocket服務(wù),首先使用Gin框架搭建http服務(wù),然后使用gorilla/websocket庫(kù)實(shí)現(xiàn)簡(jiǎn)單后端WebSocket服務(wù),具有一定的參考價(jià)值,感興趣的可以了解一下2023-05-05
go語(yǔ)言單元測(cè)試基準(zhǔn)測(cè)試及表驅(qū)動(dòng)測(cè)試示例詳解
這篇文章主要為大家介紹了go語(yǔ)言單元測(cè)試基準(zhǔn)測(cè)試及表驅(qū)動(dòng)測(cè)試示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08

