zap日志二次封装

本文介绍在项目中选择ZAP日志库的原因及其实战应用,对比Logrus,ZAP更注重高性能。文中详细展示了如何使用lumberjack库进行日志文件切割,以及如何封装ZAP的Info、Warn、Error等函数,以便于在实际项目中快速调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

目前go提供的较为活跃的日志库有Logrus和Uber开源的zap。Logrus提供了丰富的hook库可用于扩展,ZAP则侧重在高性能方面,两则使用都相对来说比较简单,提供的功能都足够使用。当前的项目中对于日志的高新更高,所以选择了zap库,并做了简单的log包封装

Logrus:github.com/sirupsen/lo…
ZAP: github.com/uber-go/zap

Note

  1. 文件切割:当前使用了lumberjack库对文件进行切割,建议可以用ELK等文件聚合中间件代替
  2. 对zap info等函数进行包装时,如果需要日志文件和函数时,可以使用zap.AddCallerSkip(1)方法,跳过封装函数的调用

直接上代码


import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var log *zap.SugaredLogger

var logLevel = zap.NewAtomicLevel()

func init() {
	filePath := getFilePath()

	fmt.Println(filePath)

	w := zapcore.AddSync(&lumberjack.Logger{
		Filename:  filePath,
		MaxSize:   1024, //MB
		LocalTime: true,
		Compress:  true,
	})

	config := zap.NewProductionEncoderConfig()
	config.EncodeTime = zapcore.ISO8601TimeEncoder
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(config),
		w,
		logLevel,
	)

	logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	log = logger.Sugar()
}

type Level int8

const (
	DebugLevel Level = iota - 1

	InfoLevel

	WarnLevel

	ErrorLevel

	DPanicLevel

	PanicLevel

	FatalLevel
)

func SetLevel(level Level) {
	logLevel.SetLevel(zapcore.Level(level))
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Info(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func getFilePath() string {
	logfile := getCurrentDirectory() + "/" + getAppname() + ".log"
	return logfile
}

func getAppname() string {
	full := os.Args[0]
	full = strings.Replace(full, "\\", "/", -1)
	splits := strings.Split(full, "/")
	if len(splits) >= 1 {
		name := splits[len(splits)-1]
		name = strings.TrimSuffix(name, ".exe")
		return name
	}

	return ""
}

func Info(args ...interface{}) {
	log.Info(args...)
}

func Infof(template string, args ...interface{}) {
	log.Infof(template, args...)
}

func Warn(args ...interface{}) {
	log.Warn(args...)
}

func Warnf(template string, args ...interface{}) {
	log.Warnf(template, args...)
}

func Error(args ... interface{}) {
	log.Error(args...)
}

func Errorf(template string, args ...interface{}) {
	log.Errorf(template, args...)
}

func Panic(args ...interface{}) {
	log.Panic(args...)
}

func Panicf(template string, args ...interface{}) {
	log.Panicf(template, args...)
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值