根据Uber-go Zap的文档,它的性能比类似的结构化日志包更好——也比标准库更快。
[Zap Performance]

方法说明

方法 说明
logger.NewJSONLogger(opts …Option) 实例化 JSON 类型的 zap logger
logger.NewMeta(key string, value interface{}) 创建 Meta 标签
logger.WrapMeta(err error, metas …Meta) 包装多个Meta 标签

配置说明

配置项 配置方法
设置 Debug 日志级别 logger.WithDebugLevel()
设置 Info 日志级别(默认) logger.WithInfoLevel()
设置 Warn 日志级别 logger.WithWarnLevel()
设置 Error 日志级别 logger.WithErrorLevel()
设置关闭日志输出到控制台 logger.WithDisableConsole()
设置日志字段(key => value) logger.WithField(key, value string)
设置日志输出到文件 logger.WithFileP(file string)
设置日志输出到文件(滚动形式) logger.WithFileRotationP(file string)
设置日志时间格式 logger.WithTimeLayout(timeLayout string)

使用示例

  1. loggers, err := logger.NewJSONLogger(
  2. logger.WithInfoLevel(),
  3. logger.WithField("domain", config.ProjectName()),
  4. logger.WithTimeLayout("2006-01-02 15:04:05"),
  5. logger.WithFileP(fmt.Sprintf("./logs/%s-access.log", config.ProjectName())),
  6. )

测试用例

  1. func TestJSONLogger(t *testing.T) {
  2. logger, err := NewJSONLogger(
  3. WithInfoLevel(),
  4. WithField("defined_key", "defined_value"),
  5. )
  6. if err != nil {
  7. t.Fatal(err)
  8. }
  9. defer logger.Sync()
  10. err = errors.New("pkg error")
  11. logger.Error("err occurs", WrapMeta(nil, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
  12. logger.Error("err occurs", WrapMeta(err, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
  13. }
  14. // Output
  15. === RUN TestJSONLogger
  16. {"level":"error","time":"2021-03-21T11:55:58+08:00","caller":"logger/logger_test.go:19","msg":"err occurs","defined_key":"defined_value","meta":{"para1":"value1","para2":"value2"}}
  17. {"level":"error","time":"2021-03-21T11:55:58+08:00","caller":"logger/logger_test.go:20","msg":"err occurs","defined_key":"defined_value","error":"pkg error","errorVerbose":"pkg error\ngolang-gin-api/pkg/logger.TestJSONLogger\n\t/Users/charles/go/go-project/golang-gin-api/pkg/logger/logger_test.go:18\ntesting.tRunner\n\t/usr/local/go/src/testing/testing.go:1123\nruntime.goexit\n\t/usr/local/go/src/runtime/asm_amd64.s:1374","meta":{"para1":"value1","para2":"value2"}}
  18. --- PASS: TestJSONLogger (0.00s)
  19. PASS

基准测试

  1. func BenchmarkJsonLogger(b *testing.B) {
  2. b.ResetTimer()
  3. logger, err := NewJSONLogger(
  4. WithField("defined_key", "defined_value"),
  5. )
  6. if err != nil {
  7. b.Fatal(err)
  8. }
  9. defer logger.Sync()
  10. }
  11. goos: darwin
  12. goarch: amd64
  13. pkg: golang-gin-api/pkg/logger
  14. BenchmarkJsonLogger
  15. BenchmarkJsonLogger-4 1000000000 0.000049 ns/op
  16. PASS

参考