其他分享
首页 > 其他分享> > Go日志库——zap的配置笔记(zap.Logger、zap.SugaredLogger)

Go日志库——zap的配置笔记(zap.Logger、zap.SugaredLogger)

作者:互联网

代码

package main

import (
	// "github.com/natefinch/lumberjack"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var log *zap.Logger
var logs *zap.SugaredLogger

var db *sqlx.DB

func main() {
	InitLogger()
	defer log.Sync()

}

func InitLogger() {
	// 1. writeSyncer循环文件
	// file, _ := os.Create("./test.log")
	// writeSyncer := zapcore.AddSync(file)
	// lumberJackLogger := &lumberjack.Logger{
	// 	Filename:   "./test.log",
	// 	LocalTime:  true,
	// 	MaxSize:    1, //M
	// 	MaxBackups: 5, //个
	// 	MaxAge:     0, //天
	// 	Compress:   false,
	// }
	// writeSyncer := zapcore.AddSync(lumberJackLogger)

	// 2. console 打印 调试
	writeSyncer := zapcore.AddSync(os.Stdout)

	// 3. encoder JSON格式
	// encoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())

	// 4. encoder Console格式
	// encoder := zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())

	// 5. 自定义格式
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoder := zapcore.NewJSONEncoder(encoderConfig)

	// 6.core
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	// 7.log
	log = zap.New(core)
	logs = log.Sugar()
}

标签:zapcore,log,SugaredLogger,writeSyncer,encoder,Go,zap,encoderConfig
来源: https://blog.csdn.net/xuehu96/article/details/122421705