当前位置:网站首页>Logger and zap log Library in go language
Logger and zap log Library in go language
2022-04-23 04:33:00 【Heavy dust】
Catalog
Go In language logger and zap Log Library
In the process of software development , Critical logging is required , Facilitate later audit and troubleshooting .
A good logger should have the following functions :
- Logs are written to files instead of console output
- Log cutting - By file size 、 Cutting log files such as time or interval
- Supports different log levels , Such as :INFO,DEBUG,ERROR etc.
- Can print basic information , Such as calling file / Function name and line number , Log time, etc
Go Logger
Configure log output file
func SetupLogger() {
logFileLocation, _ := os.OpenFile("./test.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0744)
log.SetOutput(logFileLocation)
}
Write an example , Build one to URL Of HTTP Connect , Record status code / Errors are logged to the log file
func simpleHttpGet(url string) {
resp, err := http.Get(url)
if err != nil {
log.Printf("Error fetching url %s : %s", url, err.Error())
} else {
log.Printf("Status Code for %s : %s", url, resp.Status)
resp.Body.Close()
}
}
main function , Execute the sample
func main() {
SetupLogger()
simpleHttpGet("www.google.com")
simpleHttpGet("http://www.google.com")
}
notice test.log
The file is created , And recorded the following
2022/04/22 11:33:52 Error fetching url www.google.com : Get "www.google.com": unsupported protocol scheme ""
2022/04/22 11:33:53 Status Code for http://www.google.com : 200 OK
Zap Logger
go get -u go.uber.org/zap
Zap There are two types of loggers available - Sugared Logger
and Logger
In a context where performance is good but not critical , Use SugaredLogger
. It's faster than other structured logging packages 4-10 times , And support structured and printf Style logging
In the context where every microsecond and every memory allocation is important , Use Logger
. Even better than SugaredLogger
faster , Less memory allocation , But it only supports strongly typed structured logging
Logger
- By calling
zap.NewProduction()/zap.NewDevelopment()
perhapszap.Example()
Create aLogger
- Each of the above functions will create a
logger
. The only difference is that it will record different information . for exampleproduction logger
Call function information is recorded by default 、 Date and time, etc - adopt
Logger
callInfo/Error
etc. - By default, logs are printed to the application's
console
Interface
var logger *zap.Logger
func main() {
InitLogger()
defer logger.Sync()
simpleHttpGet("www.google.com")
simpleHttpGet("http://www.google.com")
}
func InitLogger() {
logger, _ = zap.NewProduction()
}
func simpleHttpGet(url string) {
resp, err := http.Get(url)
if err != nil {
logger.Error(
"Error fetching url..",
zap.String("url", url),
zap.Error(err))
} else {
logger.Info("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}
Sugared Logger
- Most of the implementations are basically the same
- The only difference is , We call the master
logger
Of .Sugar()
Method to get aSugaredLogger
- And then use
SugaredLogger
Withprintf
Format record statement
var sugarLogger *zap.SugaredLogger
func main() {
InitLogger()
defer sugarLogger.Sync()
simpleHttpGet("www.google.com")
simpleHttpGet("http://www.google.com")
}
func InitLogger() {
logger, _ := zap.NewProduction()
sugarLogger = logger.Sugar()
}
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()
}
}
customized Logger Record in a file
- Encoder: Encoder ( How to write logs ). We will use out of the box
NewJSONEncoder()
, And use the preset - WriterSyncer: Specify where the log will be written . We use
zapcore.AddSync()
Function and pass in the open file handle - Log Level: Which level of log will be written to
var logger *zap.Logger
func main() {
InitLogger()
defer logger.Sync()
simpleHttpGet("www.google.com")
simpleHttpGet("http://www.google.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())
}
func getLogWriter() zapcore.WriteSyncer {
file, _ := os.Create("./test.log")
return zapcore.AddSync(file)
}
func simpleHttpGet(url string) {
resp, err := http.Get(url)
if err != nil {
logger.Error(
"Error fetching url..",
zap.String("url", url),
zap.Error(err))
} else {
logger.Info("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}
take JSON Encoder Change to normal Log Encoder, Only need to NewJSONEncoder()
Change to NewConsoleEncoder()
Reference resources
[1] stay Go Used in language projects Zap Log Library ( Li Wenzhou )
[2] Go Logger
[3] Go zap
版权声明
本文为[Heavy dust]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230413459787.html
边栏推荐
- 【Echart】echart 入门
- 【Echart】echart 入門
- [BIM introduction practice] Revit building wall: detailed picture and text explanation of structure, envelope and lamination
- Microbial neuroimmune axis -- the hope of prevention and treatment of cardiovascular diseases
- 阿里云IoT流转到postgresql数据库方案
- 【测绘程序设计】坐标方位角推算神器(C#版)
- 用D435i录制自己的数据集运行ORBslam2并构建稠密点云
- Opencv -- yoact case segmentation model reasoning
- AWS EKS添加集群用户或IAM角色
- RC低通滤波器的逆系统
猜你喜欢
小红书被曝整体裁员20%,大厂之间内卷也很严重
C语言: 指针的进阶
【测绘程序设计】坐标方位角推算神器(C#版)
基于英飞凌MCU GTM模块的无刷电机驱动方案开源啦
补充番外14:cmake实践项目笔记(未完待续4/22)
Unipolar NRZ code, bipolar NRZ code, 2ASK, 2FSK, 2PSK, 2DPSK and MATLAB simulation
229. Find mode II
STM32上μC/Shell移植与应用
STM32单片机ADC规则组多通道转换-DMA模式
Introduction to Cortex-M3 register set, assembly language and C language interface
随机推荐
从MySQL数据库迁移到AWS DynamoDB
为什么推荐你学嵌入式
Chlamydia infection -- causes, symptoms, treatment and Prevention
PHP export excel table
阿里云IoT流转到postgresql数据库方案
Ali's ten-year technical experts jointly created the "latest" jetpack compose project combat drill (with demo)
Summary of Android development posts I interviewed in those years (attached test questions + answer analysis)
QML进阶(四)-绘制自定义控件
Inverse system of RC low pass filter
KVM error: Failed to connect socket to ‘/var/run/libvirt/libvirt-sock‘
Go 语言中的 logger 和 zap 日志库
[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022
RC低通滤波器的逆系统
zynq平臺交叉編譯器的安裝
Installation and use of Apache bench (AB pressure test tool)
/etc/bash_completion.d目录作用(用户登录立刻执行该目录下脚本)
Redis command Encyclopedia
IEEE Transactions on Industrial Informatics(TII)投稿须知
Apache Bench(ab 压力测试工具)的安装与使用
STM32 upper μ C / shell transplantation and Application