速度极快,结构化,级别的Go日志。
Installation
go get -u go.uber.org/zap
注意,zap只支持Go的两个最小版本。
Quick Start
性能良好但不是关键的上下文中,使用 SugaredLogger。它比其他日志包快4-10倍,包含结构化和printf-style APIs。
logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)
当性能和类型安全是关键的,使用 Logger。它比SugaredLogger快两倍,分配少的多,但是它仅支持结构化日志。
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
// Structured context as strongly typed Field values.
zap.String("url", url),
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
)
Performance
用于登录到热路径的应用程序,基于反射的序列化和字符串格式化代价高昂——它们是cpu密集型的,并且进行许多小的分配。换句话说,使用encoding/json和fmt.Fprintf记录大量interface{}会使你的应用程序变慢。
Zap采取了不同的方法。它包括一个无反射的、零分配的JSON编码器,并且基本的Logger尽量避免序列化开销和分配。通过在此基础上构建高级SugaredLogger, zap让用户选择什么时候需要计算每个分配,什么时候更喜欢一个更熟悉的、松散类型的API。
通过它自己的基准测试套件来衡量,zap不仅比类似的结构化日志包性能更好,而且比标准库更快。与所有基准一样,对这些基准要持保留态度。
Log a message and 10 fields:
Package | Time | Time % to zap | Objects Allocated |
---|---|---|---|
⚡ zap | 862 ns/op | +0% | 5 allocs/op |
⚡ zap (sugared) | 1250 ns/op | +45% | 11 allocs/op |
zerolog | 4021 ns/op | +366% | 76 allocs/op |
go-kit | 4542 ns/op | +427% | 105 allocs/op |
apex/log | 26785 ns/op | +3007% | 115 allocs/op |
logrus | 29501 ns/op | +3322% | 125 allocs/op |
log15 | 29906 ns/op | +3369% | 122 allocs/op |
Log a message with a logger that already has 10 fields of context:
Package | Time | Time % to zap | Objects Allocated |
---|---|---|---|
⚡ zap | 126 ns/op | +0% | 0 allocs/op |
⚡ zap (sugared) | 187 ns/op | +48% | 2 allocs/op |
zerolog | 88 ns/op | -30% | 0 allocs/op |
go-kit | 5087 ns/op | +3937% | 103 allocs/op |
log15 | 18548 ns/op | +14621% | 73 allocs/op |
apex/log | 26012 ns/op | +20544% | 104 allocs/op |
logrus | 27236 ns/op | +21516% | 113 allocs/op |
Log a static string, without any context or printf-style templating:
Package | Time | Time % to zap | Objects Allocated |
---|---|---|---|
⚡ zap | 118 ns/op | +0% | 0 allocs/op |
⚡ zap (sugared) | 191 ns/op | +62% | 2 allocs/op |
zerolog | 93 ns/op | -21% | 0 allocs/op |
go-kit | 280 ns/op | +137% | 11 allocs/op |
standard library | 499 ns/op | +323% | 2 allocs/op |
apex/log | 1990 ns/op | +1586% | 10 allocs/op |
logrus | 3129 ns/op | +2552% | 24 allocs/op |
log15 | 3887 ns/op | +3194% | 23 allocs/op |
Development Status:Stable
所有的api都是最终确定的,并且不会在1.X系列发布。时刻感知依赖关系管理系统的用户应该将zap固定到^1。