当前位置:网站首页>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 loggerCall function information is recorded by default 、 Date and time, etc - adopt
LoggercallInfo/Erroretc. - By default, logs are printed to the application's
consoleInterface
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
loggerOf .Sugar()Method to get aSugaredLogger - And then use
SugaredLoggerWithprintfFormat 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
边栏推荐
- 383. 赎金信
- Mysql出现2013 Lost connection to MySQL server during query
- Supplément: annotation
- Single chip microcomputer serial port data processing (2) -- ucosiii + cyclic queue receiving data
- eksctl 部署AWS EKS
- Mysql---数据读写分离、多实例
- 从MySQL数据库迁移到AWS DynamoDB
- Chapter 4 - understanding standard equipment documents, filters and pipelines
- Alibaba cloud IOT transfer to PostgreSQL database scheme
- How to regulate intestinal flora? Introduction to common natural substances, probiotics and prebiotics
猜你喜欢

Installation of zynq platform cross compiler

协程与多进程的完美结合

Unipolar NRZ code, bipolar NRZ code, 2ASK, 2FSK, 2PSK, 2DPSK and MATLAB simulation

QML进阶(五)-通过粒子模拟系统实现各种炫酷的特效
![[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022](/img/eb/916a3fc1a89356fd8e74b943172ac3.png)
[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022

The perfect combination of collaborative process and multi process

QML进阶(四)-绘制自定义控件

阿里云IoT流转到postgresql数据库方案

Ali's ten-year technical experts jointly created the "latest" jetpack compose project combat drill (with demo)

Interaction of diet gut microbiota on cardiovascular disease
随机推荐
mysql ,binlog 日志查询
C language character constant
[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022
Leetcode->1 两数之和
Brushless motor drive scheme based on Infineon MCU GTM module
Summary of Android development posts I interviewed in those years (attached test questions + answer analysis)
Go 语言中的 logger 和 zap 日志库
Hard core chip removal
递归调用--排列的穷举
Xiaohongshu was exposed to layoffs of 20% as a whole, and the internal volume among large factories was also very serious
Common string processing functions in C language
Single chip microcomputer serial port data processing (2) -- ucosiii + cyclic queue receiving data
国外LEAD,联盟经理常见问答
LabVIEW 小端序和大端序区别
兼容NSR20F30NXT5G的小体积肖特基二极管
PHP export excel table
Iron and intestinal flora
顺序表的基本操作
[BIM introduction practice] wall hierarchy and FAQ in Revit
阿里云IoT流转到postgresql数据库方案