七叶笔记 » golang编程 » golang zap日志记录的基本使用

golang zap日志记录的基本使用

创建一个zap.go文件代码如下:

 package core

import (
myGlobal "Performance/global"
"fmt"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/utils"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"time"
)

func Zap() (logger *zap.Logger) {
if ok, _ := utils.PathExists(myGlobal.Config.LogDirectory); !ok { // 判断是否有Director文件夹
fmt.Printf("create %v directory\n", global.GVA_CONFIG.Zap.Director)
_ = os.Mkdir(global.GVA_CONFIG.Zap.Director, os.ModePerm)
}
// 调试级别
debugPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.DebugLevel
})
// 日志级别
infoPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.InfoLevel
})
// 警告级别
warnPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.WarnLevel
})
// 错误级别
errorPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev >= zap.ErrorLevel
})

cores := [...]zapcore.Core{
getEncoderCore(fmt.Sprintf("./%s/server_debug.log", "./zap_log"), debugPriority),
getEncoderCore(fmt.Sprintf("./%s/server_info.log", "./zap_log"), infoPriority),
getEncoderCore(fmt.Sprintf("./%s/server_warn.log", "./zap_log"), warnPriority),
getEncoderCore(fmt.Sprintf("./%s/server_error.log", "./zap_log"), errorPriority),
}
logger = zap.New(zapcore.NewTee(cores[:]...), zap.AddCaller())

if global.GVA_CONFIG.Zap.ShowLine {
logger = logger.WithOptions(zap.AddCaller())
}
return logger
}

// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig() (config zapcore.EncoderConfig) {
config = zapcore.EncoderConfig{
MessageKey:     "message",
LevelKey:       "level",
TimeKey:        "time",
NameKey:        "logger",
CallerKey:      "caller",
StacktraceKey:  global.GVA_CONFIG.Zap.StacktraceKey,
LineEnding:     zapcore.DefaultLineEnding,
EncodeLevel:    zapcore.LowercaseLevelEncoder,
EncodeTime:     CustomTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller:   zapcore.FullCallerEncoder,
}
switch {
case global.GVA_CONFIG.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
config.EncodeLevel = zapcore.LowercaseLevelEncoder
case global.GVA_CONFIG.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
case global.GVA_CONFIG.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
config.EncodeLevel = zapcore.CapitalLevelEncoder
case global.GVA_CONFIG.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
config.EncodeLevel = zapcore.CapitalColorLevelEncoder
default:
config.EncodeLevel = zapcore.LowercaseLevelEncoder
}
return config
}

// getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
if global.GVA_CONFIG.Zap.Format == "json" {
return zapcore.NewJSONEncoder(getEncoderConfig())
}
return zapcore.NewConsoleEncoder(getEncoderConfig())
}

// getEncoderCore 获取Encoder的zapcore.Core
func getEncoderCore(fileName string, level zapcore.LevelEnabler) (core zapcore.Core) {
writer := utils.GetWriteSyncer(fileName) // 使用file-rotatelogs进行日志分割
return zapcore.NewCore(getEncoder(), writer, level)
}

// 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(global.GVA_CONFIG.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}
  

使用方法如下

 func main() {
log:=core.Zap()
log.Error("这是一个错消息",zap.Error(errors.New("错误")))
log.Info("这是一个调试消息")
}  

生成文件:

相关文章