您的位置 首页 golang

Go Web 框架 Gin 实践6—编写一个简单的文件日志

Go Web 框架 Gin 实践6—编写一个简单的文件日志

在上一节 中,我们解决了API’s可以任意访问的问题,那么我们现在还有一个问题。

就是我们的日志,都是输出到控制台上的,这显然对于一个项目来说是不合理的,因此我们这一节简单封装log库,使其支持简单的文件日志!

项目地址:


新建logging包

我们在pkg下新建logging目录,新建file.go和log.go文件,写入内容:

编写file文件

1、 file.go:

Go Web 框架 Gin 实践6—编写一个简单的文件日志

  • os.Stat:返回文件信息结构描述文件。如果出现错误,会返回*PathError
type PathError struct {
 Op string
 Path string
 Err error
}
 
  • os.IsNotExist:能够接受ErrNotExist、syscall的一些错误,它会返回一个 布尔值 ,能够得知文件不存在或目录不存在
  • os.IsPermission:能够接受ErrPermission、syscall的一些错误,它会返回一个布尔值,能够得知权限是否满足
  • os.OpenFile:调用文件,支持传入文件名称、指定的模式调用文件、文件权限,返回的文件的方法可以用于I/O。如果出现错误,则为*PathError。
Go Web 框架 Gin 实践6—编写一个简单的文件日志

  • os.Getwd:返回与当前目录对应的根路径名
  • os.MkdirAll:创建对应的目录以及所需的子目录,若成功则返回nil,否则返回error
  • os.ModePerm:const定义ModePerm FileMode = 0777

编写 log文件

2、 log.go

Go Web 框架 Gin 实践6—编写一个简单的文件日志

log.New:创建一个新的日志记录器。out定义要写入日志数据的IO 句柄 。prefix定义每个生成的日志行的开头。flag定义了日志记录属性

func New(out io.Writer, prefix string, flag int) *Logger {
 return &Logger{out: out, prefix: prefix, flag: flag}
}
 
  • log.LstdFlags:日志记录的格式属性之一,其余的选项如下
Go Web 框架 Gin 实践6—编写一个简单的文件日志

当前目录结构:

Go Web 框架 Gin 实践6—编写一个简单的文件日志

我们自定义的logging包,已经基本完成了,接下来让它接入到我们的项目之中吧!

我们打开先前包含log包的代码,

  1. 打开routers目录下的article.go、tag.go、auth.go
  2. 将log包的引用删除,修改引用我们自己的日志包为gin-blog/pkg/logging
  3. 将原本的log.Println(…)改为logging.Info(…)

例如auth.go文件的修改内容:

Go Web 框架 Gin 实践6—编写一个简单的文件日志

验证功能

修改文件后,重启服务,我们来试试吧!

获取到API的Token后,我们故意传错误URL参数给接口,如:

然后我们到$GOPATH/gin-blog/runtime/logs查看日志:

Go Web 框架 Gin 实践6—编写一个简单的文件日志

日志结构一切正常,我们的记录模式都为Info,因此前缀是对的,并且我们是入参有问题,也把错误记录下来了,这样排错就很方便了!

至此,本节就完成了,这只是一个简单的扩展,实际上我们线上项目要使用的文件日志,是更复杂一些,开动你的大脑 举一反三吧!

参考

本系列示例代码

  • go-gin-example

文章来源:智云一二三科技

文章标题:Go Web 框架 Gin 实践6—编写一个简单的文件日志

文章地址:https://www.zhihuclub.com/100594.shtml

关于作者: 智云科技

热门文章

评论已关闭

41条评论

  1. Unlike other options like Viagra , which only last around four hours and require you to have at least a half hour s prior notice before sex happens Cialis allows for more spontaneous sex, thanks to its ability to last about 36 hours

  2. Generics, which are created on sildenafil and tadalafil base, can be bought at the online pharmacies, without drawing excessive attention to yourself

  3. In the furnace, the charcoal was 2020 Top buy cialis online united states burning hot, buy cialis online united states emitting a bright light

  4. mestinon nizoral zalf kruidvat Tulowitzki, after all, is guaranteed 134 million over the next seven years, including a 4 million buyout for a 2021 option year, and he has been injury-prone during his career, so heГў s not worth acquiring at any cost. Pulsatile once hourly administration of exogenous GnRH restored ovulation in Rhesus monkeys with hypothalamic lesions which abolished GnRH secretion, suggesting that it was the ebb and flow of ovarian estrogen feedback acting directly on the pituitary which triggered an LH surge 208.

  5. Established as a Proprietor firm in the year 2019 at Ahmedabad Gujarat, India, we Canadian Pharma are a leading Wholesale Trader of a wide range of Anti Cancer Capsules, Anti Cancer Tablets, etc

  6. As far as we are aware, this is the first study of the hormone modulatory effect of CEAC on BC cells and the anticarcinogenicity effect of CEAC

  7. To minimize issues, increase injection frequency to a minimum of twice a week to reduce the spikes and troughs in your hormone levels less fluctuations leads to less side effects

  8. In 2015, Full House actor John Stamos was arrested for driving erratically through Beverly Hills under the influence of GHB Symptoms can arise hours to days after continued use, but can also occur later

  9. 0 at month 12 when the difference became statistically significant P P P P Make sure to follow the rules from now on though, and read the source policy and feel free to email or PM me with any questions about it

  10. zafirlukast will increase the level or effect of buspirone by affecting hepatic intestinal enzyme CYP3A4 metabolism After 4 days of incubation, cells were harvested, and Western blotting was performed

  11. The highest concentrations of coumestrol are found in soybeans and clover Citalopram Citalopram Diazepam may increase the QTc prolonging activities of Citalopram

  12. Co delivery of baicalein and doxorubicin by hyaluronic acid decorated nanostructured lipid carriers for breast cancer therapy Furthermore, S180 cells were collected from the site of treatment injections for in vivo and ex vivo cell cycle phase distribution studies

  13. in regular Ca 2 containing saline, Ca 2 free saline, and in the presence of L type Ca 2 channels blocker, nifedipine The Times characterized Thompson as saying that campaign jousting had Гў glossed over its usefulness as a police tool, even as he forcefully criticized its excesses over the past few years

  14. Lastly the ostabolic I m on the fence about but I figured it could help with catabolism through pct and since it has the potential to suppress production moderately I figured the last week at 20mg day on nolva would be sufficient For the treatment of ringworm infections of the skin, hair, and nails, namely tinea corporis, tinea pedis, tinea cruris, tinea barbae, cradle cap or other conditions caused by Trichophyton or Microsporum fungi

  15. Barthold said The purple circle corresponds to the ERО± dependent EGF up gene signature from MCF7 breast cancer cells

  16. The rodent mite, Allodermanyssus Liponyssoides sanguineus, transmits the causative organism, Rickettsia akari

  17. Case files were reviewed in individuals who tested positive between January 1998 and July 2005 Class Particulate Form e

  18. The incidence of adverse reactions to Rifampicin is variable according to different studies and Winther, K

  19. It is not surprising that, any clear consensus about the appropriate recipients of and goals for rhGH treatment thus far in the United States has been elusive

  20. Isaac lOphsGnNWVITpNwT 6 17 2022 Sections were dehydrated using a graded series of alcohol solutions

  21. For example, Phase 1 trials of EZN 2968 a HIF 1 inhibitor and PT2977 a HIF 2 inhibitor demonstrated some clinical activity, suggested by prolonged stable disease 24 weeks in one patient with a duodenal neuroendocrine tumour and five responses one partial response, four stable disease in six patients with clear cell renal cell carcinoma

  22. Understand that a lifetime of drinking alcohol is far harsher on the liver than popping some Dbol or A bombs for a few weeks, but nonetheless, it is important to think of your liver health when taking oral steroids Dietary fat provides our bodies with energy and essential fatty acids that we can t produce on our own

  23. The unit was formed in June 2004 to focus on unsolved suspicious deaths and disappearances; there s no time limit on filing criminal charges in homicide cases Intermediate outcomes technical success, blood loss and length of stay were better in the radiofrequency group compared with the myomectomy group 57 At 1 and 2 years, both groups experienced improvements in health related quality of life and symptom severity as assessed by UFS QOL and EQ 5D scores

  24. Low dose aspirin is thought to increase the prostacyclin to thromboxane ratio in the placenta, improving blood flow and decreasing thrombosis Dietary K restriction increases NCC phosphorylation allowing for more Na reabsorption in the DCT, preventing Na for K exchange in the CNT and CCD and thus maintaining plasma K concentration

  25. Methylation specific PCR analysis of PTEN gene in MCF 7 and TAMR MCF 7 cells If you don t fit into one those scenarios, you should still consider talking to a genetic counselor, because there are many other factors that can increase risk, says Joy Larsen Haidle, a genetic counselor and the cancer expert for the National Society of Genetic Counselors

网站地图