Golang日志庫logrus的介紹與使用示例代碼
logrus概述
簡介
Logrus 是一個流行的 Go 語言日志庫,它提供了結構化日志和多種日志級別的功能。Logrus 非常靈活,支持自定義日志格式和輸出,被許多 Go 語言項目廣泛使用
特點
完全兼容log
標準庫:Logrus 可以很容易地替換掉log
標準庫,因為它實現(xiàn)了相同的接口
- 結構化日志記錄:可以很容易地記錄字段數(shù)據(jù),這些數(shù)據(jù)隨后可以被其他日志處理系統(tǒng)解析
- 多個日志級別:Logrus 支持多種日志級別,包括:
Panic
、Fatal
、Error
、Warn
、Info
、Debug
和Trace
- 易于集成:Logrus 可以與其他系統(tǒng)如syslog、Hook等集成,便于日志的集中管理和分析
- 高度可定制:可以通過 Hooks 和格式化器來自定義日志的輸出格式和內容
下載
go get github.com/sirupsen/logrus
logrus常用方法
logrus.Debugln("Debugln") logrus.Infoln("Infoln") logrus.Warnln("Warnln") logrus.Errorln("Errorln") logrus.Println("Println") // 輸出如下 time="2024-10-20T16:08:01+08:00" level=info msg=Infoln time="2024-10-20T16:08:01+08:00" level=warning msg=Warnln time="2024-10-20T16:08:01+08:00" level=error msg=Errorln time="2024-10-20T16:08:01+08:00" level=info msg=Println
debug的沒有輸出,是因為logrus默認的日志輸出等級是 info
日志級別
logrus.PanicLevel
: 記錄日志,然后調用 panic()logrus.FatalLevel
: 記錄日志,然后調用 os.Exit(1)logrus.ErrorLevel
: 記錄錯誤級別的日志logrus.WarnLevel
: 記錄警告級別的日志logrus.InfoLevel
: 記錄信息級別的日志logrus.DebugLevel
: 記錄調試級別的日志logrus.TraceLevel
: 記錄跟蹤級別的日志
package main import ( "os" "github.com/sirupsen/logrus" ) func main() { // 設置日志輸出到 os.Stdout logrus.SetOutput(os.Stdout) // 設置日志級別為 InfoLevel,這意味著 InfoLevel 及以上級別的日志會被記錄 logrus.SetLevel(logrus.InfoLevel) // 記錄不同級別的日志 logrus.Trace("This is a trace message and will not be printed.") logrus.Debug("This is a debug message and will not be printed.") logrus.Info("This is an info message and will be printed.") logrus.Warn("This is a warning message and will be printed.") logrus.Error("This is an error message and will be printed.") // 注意:通常不推薦在生產環(huán)境中使用 PanicLevel 和 FatalLevel,因為它們會導致程序退出。 // logrus.Panic("This is a panic message and will cause the program to panic.") // logrus.Fatal("This is a fatal message and will cause the program to exit.") }
字段
WithField(key string, value interface{}) *Entry
:添加一個字段到日志條目WithFields(fields log.Fields) *Entry
:添加多個字段到日志條目WithError(err error) *Entry
:添加錯誤字段到日志條目
package main import ( "os" "github.com/sirupsen/logrus" ) func main() { // 設置日志輸出到 os.Stdout logrus.SetOutput(os.Stdout) // 設置日志格式為 JSON,這對于結構化日志記錄很有用 logrus.SetFormatter(&logrus.JSONFormatter{}) // 使用 WithField 方法添加一個字段 logEntry := logrus.WithField("user", "Alice") // 使用 WithFields 方法添加多個字段 logEntry = logEntry.WithFields(logrus.Fields{ "operation": "login", "result": "success", }) // 記錄一條包含字段的日志 logEntry.Info("User logged in successfully") // 使用 WithError 方法添加一個錯誤字段 err := fmt.Errorf("something went wrong") logEntry.WithError(err).Error("An error occurred") }
輸出
日志樣式
顯示行號
logrus.SetReportCaller(true)
樣式設置
默認的是以text的形式展示,也可以設置為jsong樣式
textLogger := logrus.New() // 創(chuàng)建一個 TEXT 格式的日志記錄器 textLogger.SetFormatter(&logrus.TextFormatter{ DisableColors: false, FullTimestamp: true, }) // 創(chuàng)建一個 JSON 格式的日志記錄器 jsonLogger := logrus.New() jsonLogger.SetFormatter(&logrus.JSONFormatter{})
輸出地址
SetOutput(io.Writer)
:設置日志的輸出目的地SetFormatter(formatter Formatter)
:設置日志的格式化器
package main import ( "os" "github.com/sirupsen/logrus" ) func main() { // 創(chuàng)建一個新的 Logrus 實例 log := logrus.New() // 輸出到 os.Stdout log.SetOutput(os.Stdout) // 輸出到文件 file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err == nil { log.SetOutput(file) } else { log.Fatalf("Failed to log to file, using default stderr: %v", err) } // 輸出到自定義 io.Writer,例如 bytes.Buffer var buffer bytes.Buffer log.SetOutput(&buffer) // 記錄一些日志 log.Info("This is an info message") log.Warn("This is a warning message") log.Error("This is an error message") // 如果輸出到 bytes.Buffer,你可以獲取日志內容 logBytes := buffer.Bytes() os.Stdout.Write(logBytes) // 將 buffer 中的內容輸出到 os.Stdout }
日志顏色
默認顏色
- DebugLevel: 藍色
- InfoLevel: 綠色
- WarningLevel: 黃色
- ErrorLevel: 紅色
- FatalLevel: 紅色(通常伴隨有其他指示,比如退出程序)
- PanicLevel: 紅色(通常伴隨有 panic)
禁用顏色
log.SetFormatter(&logrus.TextFormatter{ DisableColors: true, })
自定義顏色
- 創(chuàng)建一個新的
TextFormatter
結構體 - 重寫
Format
方法,在格式化日志時添加自定義顏色代碼 - 將自定義的
Formatter
設置給 Logrus 實例
自定義格式
通過實現(xiàn) logrus.Formatter
接口來自定義日志格式
package main import ( "bytes" "fmt" "github.com/sirupsen/logrus" "os" ) // CustomFormatter 自定義格式化器 type CustomFormatter struct { logrus.TextFormatter } // Format 實現(xiàn) logrus.Formatter 接口 func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) { var b *bytes.Buffer if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } // 添加自定義顏色代碼 color := "" switch entry.Level { case logrus.DebugLevel: color = "\x1b[34m" // 藍色 case logrus.InfoLevel: color = "\x1b[32m" // 綠色 case logrus.WarnLevel: color = "\x1b[33m" // 黃色 case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel: color = "\x1b[31m" // 紅色 } // 寫入顏色代碼和日志內容 fmt.Fprintf(b, "%s%s\x1b[0m\n", color, entry.Message) return b.Bytes(), nil } func main() { log := logrus.New() log.SetFormatter(&CustomFormatter{ TextFormatter: logrus.TextFormatter{ DisableColors: false, FullTimestamp: true, }, }) log.Debug("This is a debug message") log.Info("This is an info message") log.Warn("This is a warning message") log.Error("This is an error message") }
MyFormatter
結構體實現(xiàn)了 Format
方法,該方法接收一個 logrus.Entry
對象,該對象包含了日志條目的所有信息,包括時間戳、日志級別、消息和字段。Format
方法將這些信息格式化為一個字符串,并返回字節(jié)數(shù)組。
[2024-10-20T17:14:22+08:00] [info] A group of walrus emerges from the ocean size=10 animal=walrus
Hook
- 在 Logrus 中,
Hook
是一個接口,允許你添加自定義的邏輯,這些邏輯會在日志記錄之前或之后執(zhí)行。通過實現(xiàn)logrus.Hook
接口,你可以創(chuàng)建自己的鉤子來執(zhí)行額外的操作,比如發(fā)送日志到遠程系統(tǒng)、寫入數(shù)據(jù)庫、執(zhí)行特定的監(jiān)控檢查等。 - 在 Logrus 中,
Hook
的基本用法涉及以下步驟: - 定義一個 Hook 結構體:這個結構體需要實現(xiàn)
Levels()
和Fire(entry *logrus.Entry) error
方法。 - 實現(xiàn)
Levels()
方法:這個方法返回一個logrus.Level
切片,表示該 Hook 將被哪些日志級別觸發(fā)。 - 實現(xiàn)
Fire(entry \*logrus.Entry) error
方法:這個方法定義了當日志被記錄時應該執(zhí)行的邏輯。 - 將 Hook 添加到 Logrus 實例:使用
log.AddHook(hook)
方法。
自定義 Hook
示例,它會在每次記錄日志時打印出當前的函數(shù)名和文件名:
package main import ( "fmt" "runtime" "github.com/sirupsen/logrus" ) // MyHook 是一個自定義的 Logrus 鉤子 type MyHook struct { } // Levels 定義了這個鉤子會被哪些日志級別觸發(fā) func (hook *MyHook) Levels() []logrus.Level { return logrus.AllLevels } // Fire 是每次日志記錄時都會調用的方法 func (hook *MyHook) Fire(entry *logrus.Entry) error { // 獲取調用者的函數(shù)名和文件名 pc, file, line, ok := runtime.Caller(8) // 8 是調用棧的深度,可能需要根據(jù)你的代碼結構進行調整 if !ok { fmt.Println("Could not get caller info") return nil } function := runtime.FuncForPC(pc).Name() fmt.Printf("Caller: %s:%d %s\n", file, line, function) return nil } func main() { log := logrus.New() // 添加自定義鉤子 log.AddHook(&MyHook{}) log.Info("This is an informational message") log.Warn("This is a warning message") }
- 在上面的代碼中,
MyHook
結構體實現(xiàn)了Levels
和Fire
方法。Levels
方法返回一個日志級別切片,表示這個鉤子會對哪些級別的日志進行響應。在這個例子中,我們使用logrus.AllLevels
,這意味著它會對所有級別的日志做出響應。
Fire
方法會在每次記錄日志時被調用。在這個方法中,我們使用 runtime.Caller
來獲取調用日志記錄函數(shù)的函數(shù)名和文件名,并打印出來。
在 main
函數(shù)中,我們創(chuàng)建了一個 Logrus 實例,并使用 AddHook
方法將自定義的 MyHook
添加到 Logrus 中。之后,當我們記錄日志時,MyHook
的 Fire
方法會被調用,并打印出調用日志的函數(shù)名和文件名。
- 代碼輸出:
Caller: D:/goproject/pkg/mod/golang.org/toolchain@v0.0.1-go1.23.2.windows-amd64/src/runtime/proc.go:272 runtime.main
time="2024-10-20T17:19:37+08:00" level=info msg="This is an informational message"
time="2024-10-20T17:19:37+08:00" level=warning msg="This is a warning message"
Caller: D:/goproject/pkg/mod/golang.org/toolchain@v0.0.1-go1.23.2.windows-amd64/src/runtime/proc.go:272 runtime.main
到此這篇關于Golang日志庫logrus的介紹與使用的文章就介紹到這了,更多相關Golang日志庫logrus內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
go語言interface接口繼承多態(tài)示例及定義解析
這篇文章主要為大家介紹了go語言interface接口繼承多態(tài)示例及定義解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04詳解golang channel有無緩沖區(qū)的區(qū)別
這篇文章主要給大家介紹了golang channel有無緩沖區(qū)的區(qū)別,無緩沖是同步的,有緩沖是異步的,文中通過代碼示例給大家講解的非常詳細,需要的朋友可以參考下2024-01-01Go基礎教程系列之defer、panic和recover詳解
這篇文章主要介紹了Go基礎教程系列之defer、panic和recover,需要的朋友可以參考下2022-04-04