日志概述
日志的级别从低到高可分为:
- debug
- info
- warn
- error
- fatal
实际使用中可根据不同的场景,使用不同级别的日志来记录。
使用日志框架的目的:
一般程序语言自带的日志函数,在效率、易用性及功能上并不能满足项目需求,所以通常需要借助第三方日志框架来实现。
这次我们选择使用 uber 的日志框架 zap。
Zap 简介
Blazing fast, structured, leveled logging in Go.
Zap 用法实例
func init() {
var core zapcore.Core
hook := lumberjack.Logger{
Filename: "./logs/rs.log",
MaxSize: 100, // megabytes
MaxBackups: 3,
MaxAge: 7, //days
Compress: true, // disabled by default
LocalTime: true,
}
fileWriter := zapcore.AddSync(&hook)
consoleDebugging := zapcore.Lock(os.Stdout)
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoder := zapcore.NewJSONEncoder(encoderConfig)
// Join the outputs, encoders, and level-handling functions into
// zapcore.Cores, then tee the four cores together.
highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.InfoLevel
})
lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.DebugLevel
})
core = zapcore.NewTee(
zapcore.NewCore(encoder, consoleDebugging, lowPriority),
zapcore.NewCore(encoder, fileWriter, highPriority),
)
caller := zap.AddCaller()
callerSkipOpt := zap.AddCallerSkip(1)
// From a zapcore.Core, it's easy to construct a Logger.
zapLogger = zap.New(core, caller, callerSkipOpt, zap.AddStacktrace(zap.ErrorLevel))
}
func main() {
defer zapLogger.Sync()
zapLogger.Info("print info msg", zap.String("say", "hello world"))
zapLogger.Debug("print debug msg", zap.String("say", "hello"))
}
上述代码实例实现了:
- rolling log
- 根据不同的日志级别输出的不同的地方
- structured output message