模块介绍

logger 是基于 zap 日志包进行封装的。

方法说明

方法 说明
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", configs.ProjectName()),
  4. logger.WithTimeLayout("2006-01-02 15:04:05"),
  5. logger.WithFileP(fmt.Sprintf("./logs/%s-access.log", configs.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. // 输出
  15. === RUN TestJSONLogger
  16. {"level":"error","time":"2021-01-30T15:51:50+08:00","caller":"logger/logger_test.go:20","msg":"err occurs","defined_key":"defined_value","meta":{"para1":"value1","para2":"value2"}}
  17. {"level":"error","time":"2021-01-30T15:51:50+08:00","caller":"logger/logger_test.go:21","msg":"err occurs","defined_key":"defined_value","error":"pkg error","errorVerbose":"pkg error\ngithub.com/xinliangnote/go-gin-api/pkg/logger.TestJSONLogger\n\t/Users/xinliangnote/github/go-gin-api/pkg/logger/logger_test.go:19\ntesting.tRunner\n\t/usr/local/go/src/testing/testing.go:1108\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. // 输出
  12. goos: darwin
  13. goarch: amd64
  14. pkg: github.com/xinliangnote/go-gin-api/pkg/logger
  15. BenchmarkJsonLogger
  16. BenchmarkJsonLogger-12 1000000000 0.000096 ns/op
  17. PASS