根据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) |
使用示例
loggers, err := logger.NewJSONLogger(
logger.WithInfoLevel(),
logger.WithField("domain", config.ProjectName()),
logger.WithTimeLayout("2006-01-02 15:04:05"),
logger.WithFileP(fmt.Sprintf("./logs/%s-access.log", config.ProjectName())),
)
测试用例
func TestJSONLogger(t *testing.T) {
logger, err := NewJSONLogger(
WithInfoLevel(),
WithField("defined_key", "defined_value"),
)
if err != nil {
t.Fatal(err)
}
defer logger.Sync()
err = errors.New("pkg error")
logger.Error("err occurs", WrapMeta(nil, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
logger.Error("err occurs", WrapMeta(err, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
}
// Output
=== RUN TestJSONLogger
{"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"}}
{"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"}}
--- PASS: TestJSONLogger (0.00s)
PASS
基准测试
func BenchmarkJsonLogger(b *testing.B) {
b.ResetTimer()
logger, err := NewJSONLogger(
WithField("defined_key", "defined_value"),
)
if err != nil {
b.Fatal(err)
}
defer logger.Sync()
}
goos: darwin
goarch: amd64
pkg: golang-gin-api/pkg/logger
BenchmarkJsonLogger
BenchmarkJsonLogger-4 1000000000 0.000049 ns/op
PASS
参考