当前位置:网站首页>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
边栏推荐
- MYSQL50道基础练习题
- 383. 赎金信
- STM32上μC/Shell移植与应用
- [BIM introduction practice] wall hierarchy and FAQ in Revit
- IEEE Transactions on Systems, Man, and Cybernetics: Systems(TSMC)投稿须知
- Introduction to Cortex-M3 register set, assembly language and C language interface
- shell wc (统计字符数量)的基本使用
- 兼容NSR20F30NXT5G的小体积肖特基二极管
- Common string processing functions in C language
- 上海航芯技术分享 | ACM32 MCU安全特性概述
猜你喜欢
Matlab reads multiple fig graphs and then combines them into one graph (in the form of sub graph)
520.检测大写字母
win10, mysql-8.0.26-winx64.zip 安装
Inverse system of RC low pass filter
【Echart】echart 入门
MYSQL去重方法汇总
Iron and intestinal flora
STM32单片机ADC规则组多通道转换-DMA模式
递归调用--排列的穷举
Chlamydia infection -- causes, symptoms, treatment and Prevention
随机推荐
Basic use of shell WC (counting the number of characters)
Understand the gut organ axis, good gut and good health
Coinbase:关于跨链桥的基础知识、事实和统计数据
Supplément: annotation
shell wc (统计字符数量)的基本使用
Hard core chip removal
Single chip microcomputer serial port data processing (2) -- ucosiii + cyclic queue receiving data
Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.1.15.
Coinbase: basic knowledge, facts and statistics about cross chain bridge
Express中间件②(中间件的分类)
What is the thirty-six plan
Installation du compilateur croisé de la plateforme zynq
2019 is coming to an end, the longest day.
Alibaba cloud IOT transfer to PostgreSQL database scheme
【论文阅读】【3d目标检测】point transformer
STM32上μC/Shell移植与应用
[BIM introduction practice] Revit building wall: detailed picture and text explanation of structure, envelope and lamination
VHDL语言实现32位二进制数转BCD码
STM32 MCU ADC rule group multi-channel conversion DMA mode
zynq平台交叉编译器的安装