当前位置:网站首页>Go language uses zap log Library
Go language uses zap log Library
2022-06-22 05:43:00 【weixin_ forty-six million two hundred and seventy-two thousand 】
install Zap Log Library
go get -u go.uber.org/zap
To configure Zap Logger
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. It's 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 a Logger. - Each of the above functions will create a logger. The only difference is that it will record different information . for example production logger Call function information is recorded by default 、 Date and time, etc .
- adopt Logger call Info/Error etc. .
- By default, logs are printed to the terminal interface of the application .
package main
import (
"go.uber.org/zap"
"net/http"
)
var logger *zap.Logger
func main() {
InitLogger()
// Sync Call the underlying layer Core Of Sync Method , Flush all buffered log entries . The application should be careful to call... Before exiting Sync.
defer logger.Sync()
// Assign to URL send out GET request , Print log information based on success or error results
simpleHttpGet("www.baidu.com")
simpleHttpGet("http://www.baidu.com")
}
func InitLogger() {
// adopt zap.NewProduction() Create a logger
logger, _ = zap.NewProduction()
}
func simpleHttpGet(url string) {
resp, err := http.Get(url)
if err != nil {
logger.Error(
"Error fetching url..", // Output custom error prompt
zap.String("url", url), // Key information about this error
zap.Error(err)) // Key information about this error
} else {
logger.Info("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}

You can see the level at which the log is printed , Spend time , The position , And the error messages we customized .
The syntax of the logger method :
func (log *Logger) MethodXXX(msg string, fields ...Field)
among MethodXXX It's a variable parameter function , It can be Info / Error/ Debug / Panic etc. . Each method accepts a message string and any number of zapcore.Field Parameters .
Every zapcore.Field It's actually a set of key values versus parameters .
Sugared Logger
Sugar Packaged Logger In order to provide more in line with people's use habits but slightly slower API. Yes Logger It's very cheap to add sugar , So a single application uses Loggers and SugaredLoggers It's reasonable , Transform between performance sensitive code at their boundaries .
package main
import (
"go.uber.org/zap"、
"net/http"
)
var sugarLogger *zap.SugaredLogger
func main() {
InitLogger()
// Sync Call the underlying layer Core Of Sync Method , Flush all buffered log entries . The application should be careful to call... Before exiting Sync.
defer sugarLogger.Sync()
// Assign to URL send out GET request , Print log information based on success or error results
simpleHttpGet("www.baidu.com")
simpleHttpGet("http://www.baidu.com")
}
func InitLogger() {
logger, _ := zap.NewProduction()
sugarLogger = logger.Sugar()
}
func simpleHttpGet(url string) {
resp, err := http.Get(url)
if err != nil {
sugarLogger.Errorf(
"Error fetching url..",
zap.String("url", url),
zap.Error(err))
} else {
sugarLogger.Infof("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}

customized logger
Next we will not use the default zap To configure , Instead, use custom configurations . This mainly depends on 0
func New(core zapcore.Core, options ...Option) *Logger Method to implement .
New From providing zapcore Construct a new Logger . If it's delivered zapcore.Core by nil, Then go back to the implementation of no operation .
logger := zap.New(core)
We are now going to replace the previous InitLogger function
func InitLogger() {
writeSyncer := getLogWriter()
encoder := getEncoder()
// Need to transfer in Encoder、WriterSyncer、Log Level
core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
// Use zap.New(…) Method to manually pass all configuration
logger := zap.New(core)
sugarLogger = logger.Sugar()
}
// Use JSON Format write log
func getEncoder() zapcore.Encoder {
return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}
// Write log to test.log In file
func getLogWriter() zapcore.WriteSyncer {
file, _ := os.Create("./test.log")
return zapcore.AddSync(file)
}

Change the format of the log
take JSON Encoder Change to normal Log Encoder
// Write logs in different formats
func getEncoder() zapcore.Encoder {
//return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
return zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())
}

You can see that the format in the log file has changed , It's not the same as before JSON Format
More detailed configuration
We will add the following configuration
- Encode time in a form that adults can understand
- Record the log level in the log file
// Custom log format
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
// ISO8601TimeEncoder Serialization time . In milliseconds ISO8601 Format string time .
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
// CapitalLevelEncoder take Level Serialize to an all uppercase string . for example , InfoLevel Serialized as “INFO”.
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
The log adds information about the calling function
// Add the function to log the information of the calling function .
logger := zap.New(core, zap.AddCaller())

Complete code
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net/http"
"os"
)
var sugarLogger *zap.SugaredLogger
func main() {
InitLogger()
// Sync Call the underlying layer Core Of Sync Method , Flush all buffered log entries . The application should be careful to call... Before exiting Sync.
defer sugarLogger.Sync()
// Assign to URL send out GET request , Print log information based on success or error results
simpleHttpGet("www.baidu.com")
simpleHttpGet("http://www.baidu.com")
}
func InitLogger() {
// Write location
writeSyncer := getLogWriter()
// Coding format
encoder := getEncoder()
// Need to transfer in Encoder、WriterSyncer、Log Level
core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
// Use zap.New(…) Method to manually pass all configuration
// increase Caller Information
logger := zap.New(core, zap.AddCaller())
sugarLogger = logger.Sugar()
}
// Custom log format
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
// ISO8601TimeEncoder Serialization time . In milliseconds ISO8601 Format string time .
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
// CapitalLevelEncoder take Level Serialize to an all uppercase string . for example , InfoLevel Serialized as “INFO”.
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
// Write log to test.log In file
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 {
sugarLogger.Errorf(
"Error fetching url..",
zap.String("url", url),
zap.Error(err))
} else {
sugarLogger.Infof("Success..",
zap.String("statusCode", resp.Status),
zap.String("url", url))
resp.Body.Close()
}
}
Cutting log
Execute the following command to install Lumberjack
go get -u github.com/natefinch/lumberjack
If only one file is used for logging , Then the file will get bigger and bigger , Finally, it is inconvenient to locate the error . So we need to split the log , For example, divide according to time , A log file records the information of the day .
// stay zap Add Lumberjack Support
func getLogWriter() zapcore.WriteSyncer {
lumberJackLogger := &lumberjack.Logger{
Filename: "./test.log", // Location of log files
MaxSize: 1, // With MB In units of
MaxBackups: 5, // Before cutting , Maximum log file size ( With MB In units of )
MaxAge: 30, // Maximum number of days to keep old files
Compress: false, // Is it compressed? / Filing old documents
}
return zapcore.AddSync(lumberJackLogger)
}
Complete code
package main
import (
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net/http"
)
var (
sugarLogger *zap.SugaredLogger
)
func main() {
InitLogger()
defer sugarLogger.Sync() // Refresh stream , Write log to file
// Cycle write log , Here, in order to meet the cutting requirements, the cycle is recorded 100000 Time
for i := 0; i < 100000; i++ {
sugarLogger.Infof("this is a test")
}
}
func InitLogger() {
writeSyncer := getLogWriter()
encoder := getEncoder()
core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
logger := zap.New(core, zap.AddCaller())
sugarLogger = logger.Sugar()
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
// stay zap Add Lumberjack Support
func getLogWriter() zapcore.WriteSyncer {
lumberJackLogger := &lumberjack.Logger{
Filename: "./test.log",
MaxSize: 1, // With MB In units of
MaxBackups: 5, // Before cutting , Maximum log file size ( With MB In units of )
MaxAge: 30, // Maximum number of days to keep old files
Compress: false, // Is it compressed? / Filing old documents
}
return zapcore.AddSync(lumberJackLogger)
}

Reference resources
边栏推荐
- Running yolov5 reports an error attributeerror: cant get attribute sppf on module models common
- Wanzi detailed data warehouse, data lake, data middle platform and lake warehouse are integrated
- CMAKE notes
- Tensorflow 2. Chapter 14: callbacks and custom callbacks in keras
- How wechat applet assigns values to sub components
- Market consumption survey and investment prospect forecast report of China's graphite industry 2022-2027
- Sogou input method cannot output Chinese
- 大厂晋升学习方法四:Play 学习法
- Small and medium-sized enterprises should pay attention to these points when signing ERP contracts
- Traveler's budget (Los Angeles Valley)
猜你喜欢
Talk about MySQL's locking rule "hard hitting MySQL series 15"
![P1061 [noip2006 popularization group] counting method of jam](/img/53/7ca41b2ed4084f49ebcc2dd47e5919.png)
P1061 [noip2006 popularization group] counting method of jam

网络、IO流、反射、多线程、异常

Record local project startup error: invalid source distribution: 8
![P1061 [NOIP2006 普及组] Jam 的计数法](/img/53/7ca41b2ed4084f49ebcc2dd47e5919.png)
P1061 [NOIP2006 普及组] Jam 的计数法

Gerrit Code Review Setup

MinGW下载安装

OPTEE notes

vscode 远程连接错误:Server status check failed - waiting and retrying

我不建议你工作太拼命
随机推荐
Tensorflow 2.x(keras)源码详解之第十四章:keras中的回调及自定义回调
删除弹窗组件的封装使用
Use and decoupling of the mobile terminal's realm database, and use OC realm safely across threads
Golang Viper库入门教学
记本地项目启动报错:无效的源发行版: 8
P1077 [NOIP2012 普及组] 摆花
Sogou input method cannot output Chinese
Working method: 3C scheme design method
Go语言使用zap日志库
count registers in C code -- registers has one pattern
Network, IO flow, reflection, multithreading, exception
Graduation season | a new start, no goodbye
P1318 ponding area
Implementation of Nacos server source code
旅行家的预算(洛谷)
移动端布局适配
Which is the trend of cross-border policy frequent adjustment of "independent stations & platforms"?
想投放Facebook广告却不知从何入手?此文带你深入了解
count registers in C code -- registers has one pattern
Redis connection error: err client send auth, but no password is set 2 solutions