AdSense

網頁

2021/9/11

Golang uber go zap presets logger

Go uber zap preset logger效果比較。


zap有三個預先配置用來產生Logger實例的函式:


三者效果差別如下:

範例環境:

  • Go 1.16
  • zap v1.19.1


NewExample

NewExample用於範例環境。

main.go

package main

import (
    "go.uber.org/zap"
)

func main() {

    logger := zap.NewExample()
    defer logger.Sync()

    f := zap.Int("amount", 100)

    logger.Debug("debug message", f)
    logger.Info("info message", f)
    logger.Error("error message", f)
    logger.Warn("warn message", f)

}

印出結果如下。以json格式印出debug等級以上的log,僅含訊息資訊。

{"level":"debug","msg":"debug message","amount":100}
{"level":"info","msg":"info message","amount":100}
{"level":"error","msg":"error message","amount":100}
{"level":"warn","msg":"warn message","amount":100}


NewDevelopment

NewDevelopment適用於開發環境。相當於NewDevelopmentConfig().Build()

main.go

package main

import (
    "go.uber.org/zap"
)

func main() {

    logger, _ := zap.NewDevelopment()
    defer logger.Sync()

    f := zap.Int("amount", 100)

    logger.Debug("debug message", f)
    logger.Info("info message", f)
    logger.Error("error message", f)
    logger.Warn("warn message", f)

}

印出結果如下,印出debug等級以上的log,包含時間及行數資訊。

2021-09-11T18:08:13.674+0800    DEBUG   go-demo/main.go:14      debug message   {"amount": 100}
2021-09-11T18:08:13.675+0800    INFO    go-demo/main.go:15      info message    {"amount": 100}
2021-09-11T18:08:13.675+0800    ERROR   go-demo/main.go:16      error message   {"amount": 100}
main.main
        /.../go-demo/main.go:16
runtime.main
        /usr/local/Cellar/go/1.16.6/libexec/src/runtime/proc.go:225
2021-09-11T18:08:13.675+0800    WARN    go-demo/main.go:17      warn message    {"amount": 100}
main.main
        /.../go-demo/main.go:17
runtime.main
        /usr/local/Cellar/go/1.16.6/libexec/src/runtime/proc.go:225


NewProduction

NewProduction適用於生產環境。相當於NewProductionConfig().Build()

main.go

package main

import (
    "go.uber.org/zap"
)

func main() {

    logger, _ := zap.NewProduction()
    defer logger.Sync()

    f := zap.Int("amount", 100)

    logger.Debug("debug message", f)
    logger.Info("info message", f)
    logger.Error("error message", f)
    logger.Warn("warn message", f)

}

印出結果如下。以json格式印出info含以上等級的log,包含執行時間毫秒及行數資訊。

{"level":"info","ts":1631354950.341059,"caller":"go-demo/main.go:15","msg":"info message","amount":100}
{"level":"error","ts":1631354950.3411882,"caller":"go-demo/main.go:16","msg":"error message","amount":100,"stacktrace":"main.main\n\t/.../go-demo/main.go:16\nruntime.main\n\t/usr/local/Cellar/go/1.16.6/libexec/src/runtime/proc.go:225"}
{"level":"warn","ts":1631354950.341249,"caller":"go-demo/main.go:17","msg":"warn message","amount":100}

如要更細微的自訂log訊息,可利用zap.Config來配置。


沒有留言:

AdSense