Basic demo

Var logger * zap.logger func main() {initLogger() // Defer logger.sync () Func initLogger() {// There is also a New developer environment log Logger, _ = zap.newProduction ()} func httpGet(URL string) {resp, err := http.get (url) if err! = nil { logger.Error("Error fetching url.." , zap.String("url", url), zap.Error(err)) } else { logger.Info("Success.." , zap.String("statusCode", resp.Status), zap.String("url", url)) resp.Body.Close() } }Copy the code

Custom Logger

Var logger * zap.logger func main() {initLogger() // Defer logger.sync () httpGet("https://www.baidu.com") httpGet("https://www.google.com") } func initLogger() { writeSync := getLogWriter() Encoder := getEncoder() // The third argument can specify the level from which to start logging core := zapcore.NewCore(encoder, writeSync, ErrorLevel) logger = zap.new (core)} // Return a JSON encoded format. Func getEncoder() zapcore.encoder {return Zapcore. NewJSONEncoder (zap. NewProductionEncoderConfig ()} / / where is the log wrote func getLogWriter () zapcore. WriteSyncer {/ / Here we're just re-opening the file every time, you can append the file with open and Append, _ := os.create ("./test.log") return zapcore.addsync (file)} func httpGet(URL string) {resp, err := http.Get(url) if err ! = nil { logger.Error("Error fetching url.." , zap.String("url", url), zap.Error(err)) } else { logger.Info("Success.." , zap.String("statusCode", resp.Status), zap.String("url", url)) resp.Body.Close() } }Copy the code

Here ts stands for timestamp, but the readability of this timestamp is very poor, of course you can change this configuration

/ / return a json encoding format Generally use the func getEncoder () zapcore. Encoder {config: = zap NewProductionEncoderConfig () config.EncodeTime = zapcore.ISO8601TimeEncoder return zapcore.NewJSONEncoder(config) }Copy the code

We can even print in the log which method called the log method

Just change the following method:

logger = zap.New(core,zap.AddCaller())
Copy the code

Log cutting

If you keep writing information into a file, the file will quickly swell to XXX GB which is obviously unbearable, so we also need log cutting archiving

go get -u github.com/natefinch/lumberjack

func getLogWriterByJack() zapcore.WriteSyncer { logger := &lumberjack.Logger{ Filename: "./test.log", MaxSize: 10,// The unit is MB MaxBackups: 5,// Backup quantity Files are backed up before cutting MaxAge: 30, // Backup days Compress: } return zapcore.addsync (logger)}Copy the code

Write a test function to test it

for i := 0; i < 10000000; i++ {
   //httpGet("https://www.baidu.com")
   //httpGet("https://www.google.com")

   logger.Info("i:")
}
Copy the code

Integrate ZAP in GIN

There are many similar articles here and even some people directly do a similar function github.com/gin-contrib…

If you’re interested, you can try it. It’s very simple, I won’t talk about it too much, but if you need it, you can just take it.

On the whole, it is not difficult to realize the corresponding logger and recovery. You can download the source code by yourself

Change it a little bit and adapt it to your own project