搜尋
首頁後端開發Golang帶你研究一下go zap的SugaredLogger!

本文主要研究一下golang的zap的SugaredLogger

SugaredLogger

zap@v1.16.0/sugar.go

#
type SugaredLogger struct {
    base *Logger
}

func (s *SugaredLogger) Named(name string) *SugaredLogger {
    return &SugaredLogger{base: s.base.Named(name)}
}

func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger {
    return &SugaredLogger{base: s.base.With(s.sweetenFields(args)...)}
}

func (s *SugaredLogger) Debug(args ...interface{}) {
    s.log(DebugLevel, "", args, nil)
}

func (s *SugaredLogger) Info(args ...interface{}) {
    s.log(InfoLevel, "", args, nil)
}

func (s *SugaredLogger) Warn(args ...interface{}) {
    s.log(WarnLevel, "", args, nil)
}

func (s *SugaredLogger) Error(args ...interface{}) {
    s.log(ErrorLevel, "", args, nil)
}

func (s *SugaredLogger) DPanic(args ...interface{}) {
    s.log(DPanicLevel, "", args, nil)
}

func (s *SugaredLogger) Panic(args ...interface{}) {
    s.log(PanicLevel, "", args, nil)
}

func (s *SugaredLogger) Fatal(args ...interface{}) {
    s.log(FatalLevel, "", args, nil)
}

func (s *SugaredLogger) Debugf(template string, args ...interface{}) {
    s.log(DebugLevel, template, args, nil)
}

func (s *SugaredLogger) Infof(template string, args ...interface{}) {
    s.log(InfoLevel, template, args, nil)
}

func (s *SugaredLogger) Warnf(template string, args ...interface{}) {
    s.log(WarnLevel, template, args, nil)
}

func (s *SugaredLogger) Errorf(template string, args ...interface{}) {
    s.log(ErrorLevel, template, args, nil)
}

func (s *SugaredLogger) DPanicf(template string, args ...interface{}) {
    s.log(DPanicLevel, template, args, nil)
}

func (s *SugaredLogger) Panicf(template string, args ...interface{}) {
    s.log(PanicLevel, template, args, nil)
}

func (s *SugaredLogger) Fatalf(template string, args ...interface{}) {
    s.log(FatalLevel, template, args, nil)
}

func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) {
    s.log(DebugLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{}) {
    s.log(InfoLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{}) {
    s.log(WarnLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{}) {
    s.log(ErrorLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{}) {
    s.log(DPanicLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{}) {
    s.log(PanicLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) {
    s.log(FatalLevel, msg, nil, keysAndValues)
}

func (s *SugaredLogger) Sync() error {
    return s.base.Sync()
}
SugaredLogger提供了debug、info、warn、error、panic、dpanic、fatal這幾種方法(使用fmt.Sprint的預設格式),另外還有帶f的支援format,帶w的方法則支援with鍵值對

level

zap@v1.16.0/level.go

const (
    // DebugLevel logs are typically voluminous, and are usually disabled in
    // production.
    DebugLevel = zapcore.DebugLevel
    // InfoLevel is the default logging priority.
    InfoLevel = zapcore.InfoLevel
    // WarnLevel logs are more important than Info, but don't need inpidual
    // human review.
    WarnLevel = zapcore.WarnLevel
    // ErrorLevel logs are high-priority. If an application is running smoothly,
    // it shouldn't generate any error-level logs.
    ErrorLevel = zapcore.ErrorLevel
    // DPanicLevel logs are particularly important errors. In development the
    // logger panics after writing the message.
    DPanicLevel = zapcore.DPanicLevel
    // PanicLevel logs a message, then panics.
    PanicLevel = zapcore.PanicLevel
    // FatalLevel logs a message, then calls os.Exit(1).
    FatalLevel = zapcore.FatalLevel
)
zap內部的level分為debug、info、warn、 error、dpanic、panic、fatal這幾種

DPanic

DPanic stands for "panic in development." In development, it logs at PanicLevel; otherwise, it logs at ErrorLevel. DPanic makes it easier to catch errors that are theoretically possible, but shouldn't actually happen, without crashing in production.

DPanic in development

func dpanicInDevelopment() {
    logger, _ := zap.NewDevelopment()
    defer logger.Sync() // flushes buffer, if any
    sugar := logger.Sugar()
    sugar.DPanic("test dpanic")
    sugar.Info("this will not be logged")
}
DPanic在development下的效果跟著, info不會被輸出

DPanic in production

func dpanicInProduction() {
    logger, _ := zap.NewProduction()
    defer logger.Sync() // flushes buffer, if any
    sugar := logger.Sugar()
    sugar.DPanic("test dpanic logged as error in not development mode")
    sugar.Info("this will be logged")
}
DPanic在非development下則退化為error模式,最後的info照樣會輸出,這樣子在production下比較安全一點。

logger.check

zap@v1.16.0/logger.go

func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
    // check must always be called directly by a method in the Logger interface
    // (e.g., Check, Info, Fatal).
    const callerSkipOffset = 2

    // Check the level first to reduce the cost of disabled log calls.
    // Since Panic and higher may exit, we skip the optimization for those levels.
    if lvl <blockquote>logger.check方法會判斷lvl,如果是zapcore.DPanicLevel,則會進一步判斷是否是development模式,如果是會設定<code>ce.Should(ent, zapcore.WriteThenPanic)</code>
</blockquote><h2 id="小結">小結</h2>
  • zap內部的level分為debug、info、 warn、error、dpanic、panic、fatal這幾種
  • SugaredLogger提供了debug、info、warn、error、panic、dpanic、fatal這幾種方法(使用fmt.Sprint的預設格式),另外還有帶f的支援format,帶w的方法則支援with鍵值對
  • DPanic在development下的效果跟panic效果類似,在非development下則退化為error模式

以上是帶你研究一下go zap的SugaredLogger!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
Golang vs. Python:並發和多線程Golang vs. Python:並發和多線程Apr 17, 2025 am 12:20 AM

Golang更適合高並發任務,而Python在靈活性上更有優勢。 1.Golang通過goroutine和channel高效處理並發。 2.Python依賴threading和asyncio,受GIL影響,但提供多種並發方式。選擇應基於具體需求。

Golang和C:性能的權衡Golang和C:性能的權衡Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

Golang vs. Python:申請和用例Golang vs. Python:申請和用例Apr 17, 2025 am 12:17 AM

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang vs. Python:主要差異和相似之處Golang vs. Python:主要差異和相似之處Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang vs. Python:易於使用和學習曲線Golang vs. Python:易於使用和學習曲線Apr 17, 2025 am 12:12 AM

Golang和Python分別在哪些方面更易用和學習曲線更平緩? Golang更適合高並發和高性能需求,學習曲線對有C語言背景的開發者較平緩。 Python更適合數據科學和快速原型設計,學習曲線對初學者非常平緩。

表演競賽:Golang vs.C表演競賽:Golang vs.CApr 16, 2025 am 12:07 AM

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang vs.C:代碼示例和績效分析Golang vs.C:代碼示例和績效分析Apr 15, 2025 am 12:03 AM

Golang適合快速開發和並發編程,而C 更適合需要極致性能和底層控制的項目。 1)Golang的並發模型通過goroutine和channel簡化並發編程。 2)C 的模板編程提供泛型代碼和性能優化。 3)Golang的垃圾回收方便但可能影響性能,C 的內存管理複雜但控制精細。

Golang的影響:速度,效率和簡單性Golang的影響:速度,效率和簡單性Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具