zap logger项目地址 go.uber.org/zap
NewDevelopment和NewProduction区别
zap.NewDevelopment() 包含代码中文件信息
2018-01-18T15:40:05.991+0800 INFO tool/zaplog.go:83 to sugar failed to fetch URLurlhttp://example.comattempt3backoff1s
2018-01-18T15:40:05.991+0800 INFO tool/zaplog.go:88 to sugar failed to fetch URL {"url": "http://example.com", "attempt": 3, "backoff": "1s"}
2018-01-18T15:40:05.991+0800 INFO tool/zaplog.go:94 to desugar failed to fetch URL {"url": "http://example.com", "attempt": 3, "backoff": "1s"}
zap.NewProduction() 去除了文件信息
{"level":"info","ts":1516261205.991458,"caller":"tool/zaplog.go:109","msg":"to sugar failed to fetch URLurlhttp://example.comattempt3backoff1s"}
{"level":"info","ts":1516261205.9914737,"caller":"tool/zaplog.go:114","msg":"to sugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":1}
{"level":"info","ts":1516261205.991483,"caller":"tool/zaplog.go:120","msg":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":1}
动态改变日志的打印级别
利用 zap中的atom,
首先创建一个atom
atom := zap.NewAtomicLevel()
创建core的时候,第三个参数传递atom而不是zap.DebugLevel这类的固定值。
core := zapcore.NewCore(
zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig()), //开发者Encoder,包含函数调用信息
// zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
w,
// zap.InfoLevel, //info,error
atom, //debug,info,warn,error
)
logger := zap.New(core)
想要改变日志的级别
atom.SetLevel(zap.DebugLevel)
完整代码参见zaplog.go中的zaplogRoteChangeLevel
由下面的输出可以看出的确改变了日志级别。
{"L":"INFO","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"WARN","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"ERROR","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"DEBUG","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"INFO","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"WARN","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"ERROR","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"L":"ERROR","T":"2018-01-18T16:18:05.324+0800","M":"to desugar failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
本文介绍了Uber的zap日志库在Golang中的使用,重点对比了NewDevelopment和NewProduction两种配置的区别,前者包含文件信息,后者则不包含。此外,还详细讲解了如何动态改变日志的打印级别,通过创建并调整zap的日志级别原子变量atom,实现日志级别的动态切换。代码示例可在zaplog.go的zaplogRoteChangeLevel函数中查看。
1993

被折叠的 条评论
为什么被折叠?



