当前位置:网站首页>Usage of go language log Uber go / zap / lumberjack
Usage of go language log Uber go / zap / lumberjack
2022-04-21 08:00:00 【Tang Weikang】
0 Demand analysis
- Log cutting can be based on file size 、 Time or interval to cut log files ;
- Supports different log levels , for example DEBUG , INFO , WARN , ERROR etc. ;
- Be able to print basic information , Such as calling file 、 Function name and line number , Log time, etc ;
- Save log information according to time or days
1 Environmental installation
go get -u go.uber.org/zap
go get -v github.com/uber-go/atomic
go get -v github.com/uber-go/multierr
go get -uv github.com/natefinch/lumberjack
If installation fails , Just take me GitHub Installation package on go.uber.org Unzip and copy to GOPATH/src Next , The whole test case is also github On
GitHub Address
https://github.com/taw19960426/learning-go-language/tree/main/uber-go
Insert a code chip here
2 Reference blog
It's written in detail
https://blog.csdn.net/wohu1104/article/details/107326794
3 Result display

4 Source code
main.go
package main
import (
"time"
"go.uber.org/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var logger *zap.Logger
// logpath Log file path
// loglevel The level of logging
func InitLogger(logpath string, loglevel string) {
// Log segmentation
hook := lumberjack.Logger{
Filename: logpath, // Log file path , Default os.TempDir()
MaxSize: 1, // Each log file is saved 1M, Default 100M
MaxBackups: 30, // Retain 30 Backup , The default is unlimited
MaxAge: 7, // Retain 7 God , The default is unlimited
Compress: true, // Is it compressed? , No compression by default
}
write := zapcore.AddSync(&hook)
// Set the log level
// debug You can print it out info debug warn
// info Levels can be printed warn info
// warn Only print warn
// debug->info->warn->error
var level zapcore.Level
switch loglevel {
case "debug":
level = zap.DebugLevel
case "info":
level = zap.InfoLevel
case "error":
level = zap.ErrorLevel
default:
level = zap.InfoLevel
}
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "linenum",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder, // Lowercase encoder
EncodeTime: zapcore.ISO8601TimeEncoder, // ISO8601 UTC Time format
EncodeDuration: zapcore.SecondsDurationEncoder, //
EncodeCaller: zapcore.FullCallerEncoder, // Full path encoder
EncodeName: zapcore.FullNameEncoder,
}
// Set the log level
atomicLevel := zap.NewAtomicLevel()
atomicLevel.SetLevel(level)
core := zapcore.NewCore(
// zapcore.NewConsoleEncoder(encoderConfig),
zapcore.NewJSONEncoder(encoderConfig),
// zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&write)), // Print to console and file
write,
level,
)
// Open development mode , stack trace
caller := zap.AddCaller()
// Open file and line number
development := zap.Development()
// Set initialization field , Such as : Add a server name
filed := zap.Fields(zap.String("serviceName", "192.168.1.199"))
// Build log If you don't need some parameters, you can delete
logger = zap.New(core, caller, development, filed)
//logger = zap.New(core, development)
logger.Info("DefaultLogger init success")
}
func main() {
// The name of the history log is :my.log, Service restart , The log will be appended , Does not delete
InitLogger("./logs/my.log", "debug")
// Strong structural form
logger.Info("test",
zap.String("string", "xiaotang"),
zap.Int("int", 3),
zap.Duration("time", time.Second),
)
// // must key-value Structure form Performance drops a little
// logger.Sugar().Infow("test-",
// "string", "kk",
// "int", 1,
// "time", time.Second,
// )
logger.Error("test02",
zap.String("string", "x666g"),
zap.Int("int", 4),
zap.Duration("time", time.Second),
)
for {
logger.Error("test02",
zap.String("string", "x666g"),
zap.Int("int", 4),
zap.Duration("time", time.Second),
)
}
}
版权声明
本文为[Tang Weikang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210658120934.html
边栏推荐
- Implementing AES encryption and decryption with PHP
- asp. Net re regular expression, filter the amount of time order number in the returned string, and convert the non-standard time format into the correct time format
- Shortcut keys for batch modification of variable name and batch replacement code in idea
- Codeforces Round #783 (Div. 2) ABC
- IIC bus design ① - IIC communication protocol
- Return value iresult of standard function
- kubesphere3. 0 forgot admin password
- Hackmyvm integrated target | driftingblues-9 (end)
- Set Google chrome dark black background
- 【2022DASCTF X SU】 三月春季挑战赛 web复现
猜你喜欢
随机推荐
2022-4-20作业
Dynamically generate three-level menu
2022年R2移动式压力容器充装考试题模拟考试题库及模拟考试
类与对象的详解(构造方法的详解)
Supplément à la fonction d'annotation
Leetcode topic -- 120 Minimum length sum of triangles, simple DP
Post sqlmap injection method
Bluetooth profile specification (AVRCP chapter) 5.1 connection and release of vctp
Acrobat Pro DC 教程::如何使用文本和图片文件创建 PDF?
CouchDB vertical ultra vires
无意中发现了一位清华妹子的资料库!
ECS uses FRP to map Apache on the local (win10 / win11) intranet to the extranet
Laravel packages multiple files and downloads them
路由器设备选型参照天梯
数据库实验一、数据库的创建及基本查询
Return value iresult of standard function
MongoDB 实验——数据备份和恢复和数据库优化
在Win10系统中用mimikatz抓取明文密码
实战JDBC连接Mysql数据库
2022起重机械指挥特种作业证考试题库及模拟考试









