# Go 語言之 zap 日誌庫簡單使用 ## 預設的 Go log log:https://pkg.go.dev/log ```go package main import ( "log" "os" ) func init() { log.SetPrefix("LOG: ") // 設置首碼 f, ...
Go 語言之 zap 日誌庫簡單使用
預設的 Go log
package main
import (
"log"
"os"
)
func init() {
log.SetPrefix("LOG: ") // 設置首碼
f, err := os.OpenFile("./log.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("open log file failed with error: %v", err)
}
log.SetOutput(f) // 設置輸出
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
// const (
// Ldate = 1 << iota // 1 << 0 = 000000001 = 1
// Ltime // 1 << 1 = 000000010 = 2
// Lmicroseconds // 1 << 2 = 000000100 = 4
// Llongfile // 1 << 3 = 000001000 = 8
// Lshortfile // 1 << 4 = 000010000 = 16
// ...
// )
}
func main() {
log.Println("1234")
// log.Fatalln("1234")
// log.Panicln("1234")
// log.Panic("1234")
// log.Panicf("1234, %d", 5678)
}
log 包是一個簡單的日誌包。
Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. Every log message is output on a separate line: if the message being printed does not end in a newline, the logger will add one. The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message.
uber-go zap
github zap:https://github.com/uber-go/zap
pkg zap:https://pkg.go.dev/go.uber.org/zap#section-readme
Blazing fast, structured, leveled logging in Go.
安裝
go get -u go.uber.org/zap
在性能良好但不是關鍵的上下文中,使用 SugaredLogger
。它比其他結構化日誌包快4-10倍,包括結構化和 printf 風格的 API。
logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)
當性能和類型安全至關重要時,請使用Logger
。它甚至比SugaredLogger
更快,分配也少得多,但它只支持結構化日誌記錄。
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
// Structured context as strongly typed Field values.
zap.String("url", url),
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
)
zap文檔:https://pkg.go.dev/go.uber.org/zap#section-readme
Logger 簡單使用
package main
import (
"go.uber.org/zap"
"net/http"
)
// 定義一個全局 logger 實例
// Logger提供快速、分級、結構化的日誌記錄。所有方法對於併發使用都是安全的。
// Logger是為每一微秒和每一個分配都很重要的上下文設計的,
// 因此它的API有意傾向於性能和類型安全,而不是簡便性。
// 對於大多數應用程式,SugaredLogger在性能和人體工程學之間取得了更好的平衡。
var logger *zap.Logger
func main() {
// 初始化
InitLogger()
// Sync調用底層Core的Sync方法,刷新所有緩衝的日誌條目。應用程式在退出之前應該註意調用Sync。
// 在程式退出之前,把緩衝區里的日誌刷到磁碟上
defer logger.Sync()
simpleHttpGet("www.baidu.com")
simpleHttpGet("http://www.baidu.com")
}
func InitLogger() {
// NewProduction構建了一個合理的生產Logger,它將infollevel及以上的日誌以JSON的形式寫入標準錯誤。
// It's a shortcut for NewProductionConfig().Build(...Option).
logger, _ = zap.NewProduction()
}
func simpleHttpGet(url string) {
// Get向指定的URL發出Get命令。如果響應是以下重定向代碼之一,則Get跟隨重定向,最多可重定向10個:
// 301 (Moved Permanently)
// 302 (Found)
// 303 (See Other)
// 307 (Temporary Redirect)
// 308 (Permanent Redirect)
// Get is a wrapper around DefaultClient.Get.
// 使用NewRequest和DefaultClient.Do來發出帶有自定義頭的請求。
resp, err := http.Get(url)
if err != nil {
// Error在ErrorLevel記錄消息。該消息包括在日誌站點傳遞的任何欄位,以及日誌記錄器上積累的任何欄位。
logger.Error(
"Error fetching url..",
zap.String("url", url), // 字元串用給定的鍵和值構造一個欄位。
zap.Error(err)) // // Error is shorthand for the common idiom NamedError("error", err).
} else {
// Info以infollevel記錄消息。該消息包括在日誌站點傳遞的任何欄位,以及日誌記錄器上積累的任何欄位。
logger.Info("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}
運行
Code/go/zap_demo via