Go日誌框架zap與lumberjack簡單配置封裝
簡介
zap
zap是uber開源的Go高效能日誌庫
https://github.com/uber-go/zaplumberjack
Lumberjack用於將日誌寫入滾動檔案。zap 不支援檔案歸檔,如果要支援檔案按大小或者時間歸檔,需要使用lumberjack,lumberjack也是zap官方推薦的。
https://github.com/natefinch/lumberjack簡單使用
工程結構

專案結構.png
核心程式碼
LogCore
/** * 獲取日誌 * filePath 日誌檔案路徑 * level 日誌級別 * maxSize 每個日誌檔案儲存的最大尺寸 單位:M * maxBackups 日誌檔案最多儲存多少個備份 * maxAge 檔案最多儲存多少天 * compress 是否壓縮 * serviceName 服務名 */ func NewLogger(filePath string, level zapcore.Level, maxSize int, maxBackups int, maxAge int, compress bool, serviceName string) *zap.Logger { core := newCore(filePath, level, maxSize, maxBackups, maxAge, compress) return zap.New(core, zap.AddCaller(), zap.Development(), zap.Fields(zap.String("serviceName", serviceName))) } /** * zapcore構造 */ func newCore(filePath string, level zapcore.Level, maxSize int, maxBackups int, maxAge int, compress bool) zapcore.Core { //日誌檔案路徑配置2 hook := lumberjack.Logger{ Filename:filePath,// 日誌檔案路徑 MaxSize:maxSize,// 每個日誌檔案儲存的最大尺寸 單位:M MaxBackups: maxBackups, // 日誌檔案最多儲存多少個備份 MaxAge:maxAge,// 檔案最多儲存多少天 Compress:compress,// 是否壓縮 } // 設定日誌級別 atomicLevel := zap.NewAtomicLevel() atomicLevel.SetLevel(level) //公用編碼器 encoderConfig := zapcore.EncoderConfig{ TimeKey:"time", LevelKey:"level", NameKey:"logger", CallerKey:"linenum", MessageKey:"msg", StacktraceKey:"stacktrace", LineEnding:zapcore.DefaultLineEnding, EncodeLevel:zapcore.LowercaseLevelEncoder,// 小寫編碼器 EncodeTime:zapcore.ISO8601TimeEncoder,// ISO8601 UTC 時間格式 EncodeDuration: zapcore.SecondsDurationEncoder, // EncodeCaller:zapcore.FullCallerEncoder,// 全路徑編碼器 EncodeName:zapcore.FullNameEncoder, } return zapcore.NewCore( zapcore.NewJSONEncoder(encoderConfig),// 編碼器配置 zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&hook)), // 列印到控制檯和檔案 atomicLevel,// 日誌級別 ) }
Log
var MainLogger *zap.Logger var GatewayLogger *zap.Logger func init() { MainLogger = NewLogger("./logs/main.log", zapcore.InfoLevel, 128, 30, 7, true, "Main") GatewayLogger = NewLogger("./logs/gateway.log", zapcore.DebugLevel, 128, 30, 7, true, "Gateway") }
AppMain
func main() { fmt.Println("init main") log.MainLogger.Debug("hello main Debug") log.MainLogger.Info("hello main Info") log.GatewayLogger.Debug("Hi Gateway Im Debug") log.GatewayLogger.Info("Hi GatewayIm Info") }
github原碼
https://github.com/ClawHub/go-study