- 下载
go get -u go.uber.org/zap
- 简单使用,只输出到终端
func main() {
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)
}
- 输出到文件中
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)
}
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),
)
}
- 配置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("初始化logger失败")
}
zap.ReplaceGlobals(logger)
}
func main() {
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)
}
}