#zap is a high-performance log library. Here is a brief introduction to the use of zap.
1. Download zap bag (Recommended Learning: Go )
## Because ZAP is open source of Uber, ZAP The package used is at go.uber.org/zap. If you directly go to get this package, you may be prompted that it cannot be obtained.
You can go get github.com/uber-go/zap, and then copy the zap directory to src/go.uber.org (you may also need go.uber.org/atomic and go.uber.org/multierr, you can refer to this method to get it)2.zap simple encapsulation example.
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...) }
Usage example after simple encapsulation:
package main import ( "logger" ) func main() { logger.Infof("simple zap logger example") }
The above is the detailed content of How to use golang's zap. For more information, please follow other related articles on the PHP Chinese website!