其他分享
首页 > 其他分享> > zap日志配置

zap日志配置

作者:互联网

转载自LINK

目录

默认的go logger

默认的log不支持日志分级,没有INFO,DEBUG,ERROR之分

package main

import (
	"log"
	"net/http"
	"os"
)

func initlog(){
	logFileLocation, _ := os.OpenFile("./test.log", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0744) //创建一个可读写的文件,且覆盖掉以前的内容
	log.SetOutput(logFileLocation) //设置输出的文件
}
func testlog( url string ){
	resp, err := http.Get( url )
	if err != nil{
		log.Printf("Error fetching url %s : %s", url, err.Error() )
	}else{
		defer resp.Body.Close()
		log.Printf("Status code for %s : %s",url,resp.Status )
	}
}
func main(){
	initlog()
	testlog("https://www.acwing.com/")
}

Zap Logger

Zap是非常快的、结构化的,分日志级别的Go日志库

安装zip

go get -u go.uber.org/zap

测试

package main

import (
	"go.uber.org/zap"
	"net/http"
)

var(
	logger *zap.Logger
)
func InitLogger(){
	logger,_ = zap.NewProduction() //初始化
}
func TestLogger( 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))
	}
}
func main(){
	InitLogger()
	defer logger.Sync()
	TestLogger("h@://www.acwing.com")
	TestLogger("http://www.acwing.com")
}

其中logger.Error的原型是

func (log *Logger) Error(msg string, fields ...Field)
//msg代表为必选的字段,后面的Field是可选字段,最后会把这些字段拼接成一个json输出

把日志写入文件

将日志写入文件而不是终端

func New(core zapcore.Core, options ...Option) *Logger

zapcore.Core需要三个配置——EncoderWriteSyncerLogLevel

1.Encoder:编码器(如何写入日志)。我们将使用开箱即用的NewJSONEncoder(),并使用预先设置的ProductionEncoderConfig()

 zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())

2.WriterSyncer:指定日志将写到哪里去。我们使用zapcore.AddSync()函数并且将打开的文件句柄传进去。

   file, _ := os.Create("./test.log")
   writeSyncer := zapcore.AddSync(file)

3.Log Level:设定哪种级别的日志将被写入。

于是,初始化logger就变成了这样

func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	logger = zap.New(core)
}

func getEncoder() zapcore.Encoder {
	return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}

func getLogWriter() zapcore.WriteSyncer {
	file, _ := os.Create("./test.log")
	return zapcore.AddSync(file)
}

最终版本

getEncoder()中加入对时间格式的设置

getLogWriter()采用Lumberjack库支持(更多配置)

package main

import (
	"net/http"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var sugarLogger *zap.SugaredLogger

func main() {
	InitLogger()
	defer sugarLogger.Sync()
	simpleHttpGet("www.sogo.com")
	simpleHttpGet("http://www.sogo.com")
}

func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	logger := zap.New(core, zap.AddCaller())
	sugarLogger = logger.Sugar()
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./test.log",
		MaxSize:    1,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}

func simpleHttpGet(url string) {
	sugarLogger.Debugf("Trying to hit GET request for %s", url)
	resp, err := http.Get(url)
	if err != nil {
		sugarLogger.Errorf("Error fetching URL %s : Error = %s", url, err)
	} else {
		sugarLogger.Infof("Success! statusCode = %s for URL %s", resp.Status, url)
		resp.Body.Close()
	}
}

标签:zapcore,log,url,配置,func,日志,logger,zap
来源: https://blog.csdn.net/jziwjxjd/article/details/122268080