golang有用的库及工具 之 zap.Logger包 使用

来源:互联网 发布:淘宝怎么打开神笔 编辑:程序博客网 时间:2024/05/18 23:14

zap.Logger  是go语言中相对日志库中性能最高的。那么如何开始使用?不多说直接上代码:


import (   "encoding/json"   "fmt"   "log"   "go.uber.org/zap"   "go.uber.org/zap/zapcore")var Logger *zap.Loggerfunc InitLogger() {   // 日志地址 "out.log" 自定义   lp := Conf.Common.LogPath   // 日志级别 DEBUG,ERROR, INFO   lv := Conf.Common.LogLevel   // 是否 DEBUG   isDebug := true   if Conf.Common.IsDebug != true {      isDebug = false   }   initLogger(lp, lv, isDebug)   log.SetFlags(log.Lmicroseconds | log.Lshortfile | log.LstdFlags)}func initLogger(lp string, lv string, isDebug bool) {   var js string   if isDebug {      js = fmt.Sprintf(`{      "level": "%s",      "encoding": "json",      "outputPaths": ["stdout"],      "errorOutputPaths": ["stdout"]      }`, lv)   } else {      js = fmt.Sprintf(`{      "level": "%s",      "encoding": "json",      "outputPaths": ["%s"],      "errorOutputPaths": ["%s"]      }`, lv, lp, lp)   }   var cfg zap.Config   if err := json.Unmarshal([]byte(js), &cfg); err != nil {      panic(err)   }   cfg.EncoderConfig = zap.NewProductionEncoderConfig()   cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder   var err error   Logger, err = cfg.Build()   if err != nil {      log.Fatal("init logger error: ", err)   }}

如何使用:

func TestInitLogger(t *testing.T) {   InitLogger("out.log", "DEBUG", false)   s := []string{      "hello info",      "hello error",      "hello debug",      "hello fatal",   }   Log.Info("info:", zap.String("s", s[0]))   Log.Error("info:", zap.String("s", s[1]))   Log.Debug("info:", zap.String("s", s[2]))   Log.Fatal("info:", zap.String("s", s[3]))}


输出:

{"level":"info","ts":"2017-10-25 13:45:42.332","caller":"logger/logger_test.go:16","msg":"info:","s":"hello info"}{"level":"error","ts":"2017-10-25 13:45:42.396","caller":"logger/logger_test.go:17","msg":"info:","s":"hello error","stacktrace":"go.uber.org/zap.Stack\n\tD:/gopath/src/go.uber.org/zap/field.go:191\ngo.uber.org/zap.(*Logger).check\n\tD:/gopath/src/go.uber.org/zap/logger.go:301\ngo.uber.org/zap.(*Logger).Error\n\tD:/gopath/src/go.uber.org/zap/logger.go:202\ngithub.com/corego/hermes/logger.TestInitLogger\n\tD:/gopath/src/github.com/corego/hermes/logger/logger_test.go:17\ntesting.tRunner\n\tD:/Program Files (x86)/go/src/testing/testing.go:746"}{"level":"debug","ts":"2017-10-25 13:45:42.396","caller":"logger/logger_test.go:18","msg":"info:","s":"hello debug"}{"level":"fatal","ts":"2017-10-25 13:45:42.396","caller":"logger/logger_test.go:19","msg":"info:","s":"hello fatal","stacktrace":"go.uber.org/zap.Stack\n\tD:/gopath/src/go.uber.org/zap/field.go:191\ngo.uber.org/zap.(*Logger).check\n\tD:/gopath/src/go.uber.org/zap/logger.go:301\ngo.uber.org/zap.(*Logger).Fatal\n\tD:/gopath/src/go.uber.org/zap/logger.go:235\ngithub.com/corego/hermes/logger.TestInitLogger\n\tD:/gopath/src/github.com/corego/hermes/logger/logger_test.go:19\ntesting.tRunner\n\tD:/Program Files (x86)/go/src/testing/testing.go:746"}



原创粉丝点击