zap logger项目地址 go.uber.org/zap
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"}