网站运营外包,上海网站建设找哪家公司,集团官方网站建设方案,网站关键词多少个最好Golang 操作 Logger、Zap Logger 日志_golang zap-CSDN博客 目录 一、 从控制器中获取参数的几种形式 1#xff09; 页面请求url直接拼接参数。 2#xff09; 页面请求提交form表单 3#xff09; 页面请求发送json数据#xff0c;使用上下文对象c的BindJSON()方法接… Golang 操作 Logger、Zap Logger 日志_golang zap-CSDN博客 目录 一、 从控制器中获取参数的几种形式 1 页面请求url直接拼接参数。 2 页面请求提交form表单 3 页面请求发送json数据使用上下文对象c的BindJSON()方法接收数据 4 页面请求发送json数据使用相应小写字段 结构体对象接收值。 二、使用自定义的logger记录日志文件 1创建 自定义的logger.go文件 2使用自定义logger 1 在common.go中文件写入logger.SimpleHttpGet() 2直接在路由请求调用的函数中写入logger.SimpleHttpGet()
三) 再次自定义logger 使用自定义logger函数 一、 从控制器中获取参数的几种形式 1 页面请求url直接拼接参数。 2 页面请求提交form表单 3 页面请求发送json数据使用上下文对象c的BindJSON()方法接收数据 4 页面请求发送json数据使用相应小写字段 结构体对象接收值。 二、使用自定义的logger记录日志文件 1创建 自定义的logger.go文件 package loggerimport (net/httpgithub.com/natefinch/lumberjackgo.uber.org/zapgo.uber.org/zap/zapcore
)var sugarLogger *zap.SugaredLogger//func main() {
// InitLogger()
// defer sugarLogger.Sync()
// simpleHttpGet(https://www.baidu.com)
// simpleHttpGet(https://c.runoob.com)
//}func InitLogger() {writeSyncer : getLogWriter()encoder : getEncoder()core : zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)logger : zap.New(core)sugarLogger logger.Sugar()
}// func getEncoder() zapcore.Encoder {
// return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
// return zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())
// }func getEncoder() zapcore.Encoder {encoderConfig : zap.NewProductionEncoderConfig()encoderConfig.EncodeTime zapcore.ISO8601TimeEncoderencoderConfig.EncodeLevel zapcore.CapitalLevelEncoderreturn zapcore.NewConsoleEncoder(encoderConfig)
}// func getLogWriter() zapcore.WriteSyncer {
//如果想要追加写入可以查看我的博客文件操作那一章
// file, _ : os.Create(./test.log)
// return zapcore.AddSync(file)
// }func getLogWriter() zapcore.WriteSyncer {lumberJackLogger : lumberjack.Logger{Filename: ./test.log,MaxSize: 1,MaxBackups: 5,MaxAge: 30,Compress: false,}return zapcore.AddSync(lumberJackLogger)
}func SimpleHttpGet(url string) {sugarLogger.Debugf(Trying to hit GET request for %s, url)resp, err : http.Get(url)if err ! nil {sugarLogger.Errorf(Error fetching URL %s : Error %s, url, err)} else {sugarLogger.Infof(Success! statusCode %s for URL %s, resp.Status, url)resp.Body.Close()}
}2使用自定义logger 1 在common.go中文件写入logger.SimpleHttpGet() 每个url请求调用的函数最终调同到ReturnSuccess()函数 logger.InitLogger()logger.SimpleHttpGet(c.Request.URL.Path) 2直接在路由请求调用的函数中写入logger.SimpleHttpGet() 三) 再次自定义logger
package loggerimport (fmtgithub.com/gin-gonic/gingithub.com/sirupsen/logrusionet/httpospathruntime/debugtime
)func init() {// 设置日志格式为json格式logrus.SetFormatter(logrus.JSONFormatter{TimestampFormat: 2006-01-02 15:04:05,})logrus.SetReportCaller(false)
}func Write(msg string, filename string) {setOutPutFile(logrus.InfoLevel, filename)logrus.Info(msg)
}func Debug(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.DebugLevel, debug)logrus.WithFields(fields).Debug(args)
}func Info(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.InfoLevel, info)logrus.WithFields(fields).Info(args)
}func Warn(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.WarnLevel, warn)logrus.WithFields(fields).Warn(args)
}func Fatal(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.FatalLevel, fatal)logrus.WithFields(fields).Fatal(args)
}func Error(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.ErrorLevel, error)logrus.WithFields(fields).Error(args)
}func Panic(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.PanicLevel, panic)logrus.WithFields(fields).Panic(args)
}func Trace(fields logrus.Fields, args ...interface{}) {setOutPutFile(logrus.TraceLevel, trace)logrus.WithFields(fields).Trace(args)
}func setOutPutFile(level logrus.Level, logName string) {if _, err : os.Stat(./runtime/log); os.IsNotExist(err) {err os.MkdirAll(./runtime/log, 0777)if err ! nil {panic(fmt.Errorf(create log dir %s error: %s, ./runtime/log, err))}}timeStr : time.Now().Format(2006-01-02)fileName : path.Join(./runtime/log, logName_timeStr.log)var err erroros.Stderr, err os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)if err ! nil {fmt.Println(open log file err, err)}logrus.SetOutput(os.Stderr)logrus.SetLevel(level)return
}func LoggerToFile() gin.LoggerConfig {if _, err : os.Stat(./runtime/log); os.IsNotExist(err) {err os.MkdirAll(./runtime/log, 0777)if err ! nil {panic(fmt.Errorf(create log dir %s error: %s, ./runtime/log, err))}}timeStr : time.Now().Format(2006-01-02)fileName : path.Join(./runtime/log, success_timeStr.log)os.Stderr, _ os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)var conf gin.LoggerConfig{Formatter: func(param gin.LogFormatterParams) string {return fmt.Sprintf(%s - %s \%s %s %s %d %s \%s\ %s\\n,param.TimeStamp.Format(2006-01-02 15:04:05),param.ClientIP,param.Method,param.Path,param.Request.Proto,param.StatusCode,param.Latency,param.Request.UserAgent(),param.ErrorMessage,)},Output: io.MultiWriter(os.Stdout, os.Stderr),}return conf
}func Recover(c *gin.Context) {defer func() {if err : recover(); err ! nil {if _, errDir : os.Stat(./runtime/log); os.IsNotExist(errDir) {errDir os.MkdirAll(./runtime/log, 0777)if errDir ! nil {panic(fmt.Errorf(create log dir %s error: %s, ./runtime/log, errDir))}}timeStr : time.Now().Format(2006-01-02)fileName : path.Join(./runtime/log, error_timeStr.log)f, errFile : os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)if errFile ! nil {fmt.Println(errFile)}timeFileStr : time.Now().Format(2006-01-02 15:04:05)f.WriteString(panic error time: timeFileStr \n)f.WriteString(fmt.Sprintf(%v, err) \n)f.WriteString(stacktrace from panic: string(debug.Stack()) \n)f.Close()c.JSON(http.StatusOK, gin.H{code: 500,msg: fmt.Sprintf(%v, err),})//终止后续接口调用不加的话recover到异常后还会继续执行接口里后续代码c.Abort()}}()c.Next()
}使用自定义logger函数 文章转载自: http://www.morning.zylrk.cn.gov.cn.zylrk.cn http://www.morning.swwpl.cn.gov.cn.swwpl.cn http://www.morning.tnbsh.cn.gov.cn.tnbsh.cn http://www.morning.ssmhn.cn.gov.cn.ssmhn.cn http://www.morning.jzbjx.cn.gov.cn.jzbjx.cn http://www.morning.lmctj.cn.gov.cn.lmctj.cn http://www.morning.fqmbt.cn.gov.cn.fqmbt.cn http://www.morning.lsmnn.cn.gov.cn.lsmnn.cn http://www.morning.yprjy.cn.gov.cn.yprjy.cn http://www.morning.xyyplp.cn.gov.cn.xyyplp.cn http://www.morning.rqqlp.cn.gov.cn.rqqlp.cn http://www.morning.jiuyungps.com.gov.cn.jiuyungps.com http://www.morning.zqnmp.cn.gov.cn.zqnmp.cn http://www.morning.zqcdl.cn.gov.cn.zqcdl.cn http://www.morning.kpgms.cn.gov.cn.kpgms.cn http://www.morning.fhddr.cn.gov.cn.fhddr.cn http://www.morning.dwyyf.cn.gov.cn.dwyyf.cn http://www.morning.lcjw.cn.gov.cn.lcjw.cn http://www.morning.ywqw.cn.gov.cn.ywqw.cn http://www.morning.pzlhq.cn.gov.cn.pzlhq.cn http://www.morning.ttkns.cn.gov.cn.ttkns.cn http://www.morning.mfqmk.cn.gov.cn.mfqmk.cn http://www.morning.tbhlc.cn.gov.cn.tbhlc.cn http://www.morning.lbbyx.cn.gov.cn.lbbyx.cn http://www.morning.ybhrb.cn.gov.cn.ybhrb.cn http://www.morning.qnrpj.cn.gov.cn.qnrpj.cn http://www.morning.qpzjh.cn.gov.cn.qpzjh.cn http://www.morning.ctpfq.cn.gov.cn.ctpfq.cn http://www.morning.ghssm.cn.gov.cn.ghssm.cn http://www.morning.mytmx.cn.gov.cn.mytmx.cn http://www.morning.slqzb.cn.gov.cn.slqzb.cn http://www.morning.ggfdq.cn.gov.cn.ggfdq.cn http://www.morning.tzzkm.cn.gov.cn.tzzkm.cn http://www.morning.wxlzr.cn.gov.cn.wxlzr.cn http://www.morning.gjssk.cn.gov.cn.gjssk.cn http://www.morning.ddtdy.cn.gov.cn.ddtdy.cn http://www.morning.prmyx.cn.gov.cn.prmyx.cn http://www.morning.hxsdh.cn.gov.cn.hxsdh.cn http://www.morning.pbzgj.cn.gov.cn.pbzgj.cn http://www.morning.skscy.cn.gov.cn.skscy.cn http://www.morning.zlgr.cn.gov.cn.zlgr.cn http://www.morning.lmhh.cn.gov.cn.lmhh.cn http://www.morning.psxcr.cn.gov.cn.psxcr.cn http://www.morning.njddz.cn.gov.cn.njddz.cn http://www.morning.swyr.cn.gov.cn.swyr.cn http://www.morning.fyglr.cn.gov.cn.fyglr.cn http://www.morning.lxqkt.cn.gov.cn.lxqkt.cn http://www.morning.dtrzw.cn.gov.cn.dtrzw.cn http://www.morning.mywnk.cn.gov.cn.mywnk.cn http://www.morning.mzydm.cn.gov.cn.mzydm.cn http://www.morning.gstmn.cn.gov.cn.gstmn.cn http://www.morning.mfbcs.cn.gov.cn.mfbcs.cn http://www.morning.gmztd.cn.gov.cn.gmztd.cn http://www.morning.bfgpn.cn.gov.cn.bfgpn.cn http://www.morning.huayaosteel.cn.gov.cn.huayaosteel.cn http://www.morning.ykwqz.cn.gov.cn.ykwqz.cn http://www.morning.lveyue.com.gov.cn.lveyue.com http://www.morning.hxxyp.cn.gov.cn.hxxyp.cn http://www.morning.rstrc.cn.gov.cn.rstrc.cn http://www.morning.qzpqp.cn.gov.cn.qzpqp.cn http://www.morning.rsjf.cn.gov.cn.rsjf.cn http://www.morning.ccjhr.cn.gov.cn.ccjhr.cn http://www.morning.hkshy.cn.gov.cn.hkshy.cn http://www.morning.ntkpc.cn.gov.cn.ntkpc.cn http://www.morning.kqpxb.cn.gov.cn.kqpxb.cn http://www.morning.yldgw.cn.gov.cn.yldgw.cn http://www.morning.prmbb.cn.gov.cn.prmbb.cn http://www.morning.mnpdy.cn.gov.cn.mnpdy.cn http://www.morning.shinezoneserver.com.gov.cn.shinezoneserver.com http://www.morning.rdlong.com.gov.cn.rdlong.com http://www.morning.rxsgk.cn.gov.cn.rxsgk.cn http://www.morning.hqllx.cn.gov.cn.hqllx.cn http://www.morning.zrgx.cn.gov.cn.zrgx.cn http://www.morning.crrmg.cn.gov.cn.crrmg.cn http://www.morning.ggnfy.cn.gov.cn.ggnfy.cn http://www.morning.jytrb.cn.gov.cn.jytrb.cn http://www.morning.rlqml.cn.gov.cn.rlqml.cn http://www.morning.tsyny.cn.gov.cn.tsyny.cn http://www.morning.ghxkm.cn.gov.cn.ghxkm.cn http://www.morning.tgydf.cn.gov.cn.tgydf.cn