uber zap logger使用指南

  • NewDevelopment和NewProduction区别
  • 动态改变日志的打印级别

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"}

你可能感兴趣的:(golang)