zap是一个高性能日志库,下面简单介绍一下zap的使用。
1.下载zap包
因为zap是uber开源的,zap内使用的包是在go.uber.org/zap,如果直接go get这个包,可能会提示get不下来。
可以go get github.com/uber-go/zap,然后再把zap目录复制到src/go.uber.org下(可能还会需要go.uber.org/atomic和go.uber.org/multierr,均可参考该方法get下来)
2.zap简单封装示例。
package logger
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
// error logger
var errorLogger *zap.SugaredLogger
var levelMap = map[string]zapcore.Level{
"debug": zapcore.DebugLevel,
"info": zapcore.InfoLevel,
"warn": zapcore.WarnLevel,
"error": zapcore.ErrorLevel,
"dpanic": zapcore.DPanicLevel,
"panic": zapcore.PanicLevel,
"fatal": zapcore.FatalLevel,
}
func getLoggerLevel(lvl string) zapcore.Level {
if level, ok := levelMap[lvl]; ok {
return level
}
return zapcore.InfoLevel
}
func init() {
fileName := "zap.log"
level := getLoggerLevel("debug")
syncWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: fileName,
MaxSize: 1 << 30, //1G
LocalTime: true,
Compress: true,
})
encoder := zap.NewProductionEncoderConfig()
encoder.EncodeTime = zapcore.ISO8601TimeEncoder
core := zapcore.NewCore(zapcore.NewJSONEncoder(encoder), syncWriter, zap.NewAtomicLevelAt(level))
logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
errorLogger = logger.Sugar()
}
func Debug(args ...interface{}) {
errorLogger.Debug(args...)
}
func Debugf(template string, args ...interface{}) {
errorLogger.Debugf(template, args...)
}
func Info(args ...interface{}) {
errorLogger.Info(args...)
}
func Infof(template string, args ...interface{}) {
errorLogger.Infof(template, args...)
}
func Warn(args ...interface{}) {
errorLogger.Warn(args...)
}
func Warnf(template string, args ...interface{}) {
errorLogger.Warnf(template, args...)
}
func Error(args ...interface{}) {
errorLogger.Error(args...)
}
func Errorf(template string, args ...interface{}) {
errorLogger.Errorf(template, args...)
}
func DPanic(args ...interface{}) {
errorLogger.DPanic(args...)
}
func DPanicf(template string, args ...interface{}) {
errorLogger.DPanicf(template, args...)
}
func Panic(args ...interface{}) {
errorLogger.Panic(args...)
}
func Panicf(template string, args ...interface{}) {
errorLogger.Panicf(template, args...)
}
func Fatal(args ...interface{}) {
errorLogger.Fatal(args...)
}
func Fatalf(template string, args ...interface{}) {
errorLogger.Fatalf(template, args...)
}
简单封装后使用示例:
package main
import (
"logger"
)
func main() {
logger.Infof("simple zap logger example")
}
本文来自php中文网的golang教程栏目:https://www.php.cn/be/go/
有疑问加站长微信联系(非本文作者)