Golang logrus 日志包及日志切割的實(shí)現(xiàn)
本文主要介紹 Golang 中最佳日志解決方案,包括常用日志包logrus 的基本使用,如何結(jié)合file-rotatelogs 包實(shí)現(xiàn)日志文件的輪轉(zhuǎn)切割兩大話題。
Golang 關(guān)于日志處理有很多包可以使用,標(biāo)準(zhǔn)庫(kù)提供的 log 包功能比較少,不支持日志級(jí)別的精確控制,自定義添加日志字段等。在眾多的日志包中,更推薦使用第三方的 logrus 包,完全兼容自帶的 log 包。logrus 是目前 Github 上 star 數(shù)量最多的日志庫(kù),logrus 功能強(qiáng)大,性能高效,而且具有高度靈活性,提供了自定義插件的功能。
很多開(kāi)源項(xiàng)目,如 docker,prometheus,dejavuzhou/ginbro 等,都是用了 logrus 來(lái)記錄其日志。
logrus 特性
- 完全兼容 golang 標(biāo)準(zhǔn)庫(kù)日志模塊:logrus 擁有六種日志級(jí)別:debug、info、warn、error、fatal 和 panic,這是 golang 標(biāo)準(zhǔn)庫(kù)日志模塊的 API 的超集。
- logrus.Debug(“Useful debugging information.”)
- logrus.Info(“Something noteworthy happened!”)
- logrus.Warn(“You should probably take a look at this.”)
- logrus.Error(“Something failed but I'm not quitting.”)
- logrus.Fatal(“Bye.”) //log之后會(huì)調(diào)用os.Exit(1)
- logrus.Panic(“I'm bailing.”) //log之后會(huì)panic()
- 可擴(kuò)展的 Hook 機(jī)制:允許使用者通過(guò) hook 的方式將日志分發(fā)到任意地方,如本地文件系統(tǒng)、標(biāo)準(zhǔn)輸出、logstash、elasticsearch 或者 mq 等,或者通過(guò) hook 定義日志內(nèi)容和格式等。
- 可選的日志輸出格式:logrus 內(nèi)置了兩種日志格式,JSONFormatter 和 TextFormatter,如果這兩個(gè)格式不滿足需求,可以自己動(dòng)手實(shí)現(xiàn)接口 Formatter 接口來(lái)定義自己的日志格式。
- Field 機(jī)制:logrus 鼓勵(lì)通過(guò) Field 機(jī)制進(jìn)行精細(xì)化的、結(jié)構(gòu)化的日志記錄,而不是通過(guò)冗長(zhǎng)的消息來(lái)記錄日志。
- logrus 是一個(gè)可插拔的、結(jié)構(gòu)化的日志框架。
- Entry: logrus.WithFields 會(huì)自動(dòng)返回一個(gè) *Entry,Entry里面的有些變量會(huì)被自動(dòng)加上
- time:entry被創(chuàng)建時(shí)的時(shí)間戳
- msg:在調(diào)用.Info()等方法時(shí)被添加
- level,當(dāng)前日志級(jí)別
logrus 基本使用
package main import ( "os" "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" ) var logger *logrus.Entry func init() { // 設(shè)置日志格式為json格式 log.SetFormatter(&log.JSONFormatter{}) log.SetOutput(os.Stdout) log.SetLevel(log.InfoLevel) logger = log.WithFields(log.Fields{"request_id": "123444", "user_ip": "127.0.0.1"}) } func main() { logger.Info("hello, logrus....") logger.Info("hello, logrus1....") // log.WithFields(log.Fields{ // "animal": "walrus", // "size": 10, // }).Info("A group of walrus emerges from the ocean") // log.WithFields(log.Fields{ // "omg": true, // "number": 122, // }).Warn("The group's number increased tremendously!") // log.WithFields(log.Fields{ // "omg": true, // "number": 100, // }).Fatal("The ice breaks!") }
基于 logrus 和 file-rotatelogs 包實(shí)現(xiàn)日志切割
很多時(shí)候應(yīng)用會(huì)將日志輸出到文件系統(tǒng),對(duì)于訪問(wèn)量大的應(yīng)用來(lái)說(shuō)日志的自動(dòng)輪轉(zhuǎn)切割管理是個(gè)很重要的問(wèn)題,如果應(yīng)用不能妥善處理日志管理,那么會(huì)帶來(lái)很多不必要的維護(hù)開(kāi)銷(xiāo):外部工具切割日志、人工清理日志等手段確保不會(huì)將磁盤(pán)打滿。
file-rotatelogs: When you integrate this to to you app, it automatically write to logs that are rotated from within the app: No more disk-full alerts because you forgot to setup logrotate!
logrus 本身不支持日志輪轉(zhuǎn)切割功能,需要配合 file-rotatelogs 包來(lái)實(shí)現(xiàn),防止日志打滿磁盤(pán)。file-rotatelogs 實(shí)現(xiàn)了 io.Writer 接口,并且提供了文件的切割功能,其實(shí)例可以作為 logrus 的目標(biāo)輸出,兩者能無(wú)縫集成,這也是 file-rotatelogs 的設(shè)計(jì)初衷:
It's normally expected that this library is used with some other logging service, such as the built-in log library, or loggers such as github.com/lestrrat-go/apache-logformat.
示例代碼:
應(yīng)用日志文件 /Users/opensource/test/go.log,每隔 1 分鐘輪轉(zhuǎn)一個(gè)新文件,保留最近 3 分鐘的日志文件,多余的自動(dòng)清理掉。
package main import ( "time" rotatelogs "github.com/lestrrat-go/file-rotatelogs" log "github.com/sirupsen/logrus" ) func init() { path := "/Users/opensource/test/go.log" /* 日志輪轉(zhuǎn)相關(guān)函數(shù) `WithLinkName` 為最新的日志建立軟連接 `WithRotationTime` 設(shè)置日志分割的時(shí)間,隔多久分割一次 WithMaxAge 和 WithRotationCount二者只能設(shè)置一個(gè) `WithMaxAge` 設(shè)置文件清理前的最長(zhǎng)保存時(shí)間 `WithRotationCount` 設(shè)置文件清理前最多保存的個(gè)數(shù) */ // 下面配置日志每隔 1 分鐘輪轉(zhuǎn)一個(gè)新文件,保留最近 3 分鐘的日志文件,多余的自動(dòng)清理掉。 writer, _ := rotatelogs.New( path+".%Y%m%d%H%M", rotatelogs.WithLinkName(path), rotatelogs.WithMaxAge(time.Duration(180)*time.Second), rotatelogs.WithRotationTime(time.Duration(60)*time.Second), ) log.SetOutput(writer) //log.SetFormatter(&log.JSONFormatter{}) } func main() { for { log.Info("hello, world!") time.Sleep(time.Duration(2) * time.Second) } }
Golang 標(biāo)準(zhǔn)日志庫(kù) log 使用
雖然 Golang 標(biāo)準(zhǔn)日志庫(kù)功能少,但是可以選擇性的了解下,下面為基本使用的代碼示例,比較簡(jiǎn)單:
package main import ( "fmt" "log" ) func init() { log.SetPrefix("【UserCenter】") // 設(shè)置每行日志的前綴 log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC) // 設(shè)置日志的抬頭字段 } func main() { log.Println("log...") log.Fatalln("Fatal Error...") fmt.Println("Not print!") }
自定義日志輸出
package main import ( "io" "log" "os" ) var ( Info *log.Logger Warning *log.Logger Error *log.Logger ) func init() { errFile, err := os.OpenFile("errors.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { log.Fatalln("打開(kāi)日志文件失?。?, err) } Info = log.New(os.Stdout, "Info:", log.Ldate|log.Ltime|log.Lshortfile) Warning = log.New(os.Stdout, "Warning:", log.Ldate|log.Ltime|log.Lshortfile) Error = log.New(io.MultiWriter(os.Stderr, errFile), "Error:", log.Ldate|log.Ltime|log.Lshortfile) } func main() { Info.Println("Info log...") Warning.Printf("Warning log...") Error.Println("Error log...") }
相關(guān)文檔
https://mojotv.cn/2018/12/27/golang-logrus-tutorial
https://github.com/lestrrat-go/file-rotatelogs
https://www.flysnow.org/2017/05/06/go-in-action-go-log.html
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Go語(yǔ)言基礎(chǔ)學(xué)習(xí)之?dāng)?shù)組的使用詳解
數(shù)組相必大家都很熟悉,各大語(yǔ)言也都有數(shù)組的身影。Go 語(yǔ)言也提供了數(shù)組類(lèi)型的數(shù)據(jù)結(jié)構(gòu)。本文就來(lái)通過(guò)一些簡(jiǎn)單的示例帶大家了解一下Go語(yǔ)言中數(shù)組的使用,希望對(duì)大家有所幫助2022-12-12golang執(zhí)行命令操作 exec.Command
這篇文章主要介紹了golang執(zhí)行命令操作 exec.Command,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12golang?手寫(xiě)貪吃蛇示例實(shí)現(xiàn)
這篇文章主要為大家介紹了golang?手寫(xiě)貪吃蛇示例實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07Go創(chuàng)建一個(gè)包并使用(導(dǎo)入本地包和注意事項(xiàng))
有時(shí)候需要自己寫(xiě)一個(gè)包方便多次使用,但是在導(dǎo)入自己寫(xiě)的包時(shí)遇到了問(wèn)題,本文主要介紹了Go創(chuàng)建一個(gè)包并使用(導(dǎo)入本地包和注意事項(xiàng)),感興趣的可以了解一下2023-11-11go使用Gin框架利用阿里云實(shí)現(xiàn)短信驗(yàn)證碼功能
這篇文章主要介紹了go使用Gin框架利用阿里云實(shí)現(xiàn)短信驗(yàn)證碼,使用json配置文件及配置文件解析,編寫(xiě)路由controller層,本文通過(guò)代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08Go語(yǔ)言學(xué)習(xí)之new函數(shù)的用法詳解
這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言中new()函數(shù)的相關(guān)知識(shí)以及具體用法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下2023-05-05Go連接數(shù)據(jù)庫(kù)操作基礎(chǔ)講解
這篇文章主要為大家介紹了Go連接數(shù)據(jù)庫(kù)操作基礎(chǔ)講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12