Bootstrap

go中zap日志的使用

  1. 下载
 go get -u go.uber.org/zap
  1. 简单使用,只输出到终端
func main() {
	//logger, _ := zap.NewProduction()
	logger, _ := zap.NewDevelopment()
	defer logger.Sync()
	logger.Info("我只是一个测试..............",
		zap.String("k1", "va1"),
	)
	url := "https://imooc.com"
	sugar := logger.Sugar()
	sugar.Infow("failed to fetch URL",
		"urI", url,
		"attempt", 3,
	)

	sugar.Infof("Failed to fetch URL: %s", url)
}
  1. 输出到文件中
func NewLogger() (*zap.Logger, error) {
	cfg := zap.NewProductionConfig()
	cfg.OutputPaths = []string{
		"./myproject.log",
		"stderr",
		"stdout",
	}
	return cfg.Build()
}

func main() {
	logger, err := NewLogger()
	if err != nil {
		panic(err)
		//panic("初始化logger失败")
	}
	su := logger.Sugar()
	defer su.Sync()
	url := "https://imooc.comssss"
	su.Info("这是一个测试。。。。。",
		zap.String("url", url),
		zap.Int("int", 1),
		zap.Duration("time", time.Second),
	)

}
  1. 配置gin的使用
package common

import (
	"gateway-gin/config"
	"go.uber.org/zap"
)

func NewLogger() (*zap.Logger, error) {
	if config.Environment == "dev" {
		cfg := zap.NewDevelopmentConfig()
		cfg.OutputPaths = []string{
			"./log/gateway.log",
			"stderr",
		}
		return cfg.Build()
	} else {
		cfg := zap.NewProductionConfig()
		cfg.OutputPaths = []string{
			"./log/gateway.log",
		}
		return cfg.Build()
	}
}

func InitLog() {
	logger, err := NewLogger()
	if err != nil {
		//panic(err)
		panic("初始化logger失败")
	}
	zap.ReplaceGlobals(logger)
}
func main() {
	// 加载多个APP的路由配置
	routers.Include(user.Routers)
	routers.NoInclude(user.NoVerifyRouters)
	// 初始化路由
	r := routers.Init()
	// 延时关闭数据库
	defer db.XormDb.Close()

	zap.L().Info("项目启动")
	if err := r.Run("0.0.0.0:8000"); err != nil {
		logrus.Info("项目启动失败:", err)
	}

}
;