Go frame simple(4) 日志logrus

Go frame simple(4) 日志logrus,第1张

1 logrus简介

logrus功能强大,性能高效,而且具有高度灵活性,提供了自定义插件的功能.
开源项目docker等都用 logrus 记录其日志。
.
Github地址:https://github.com/Sirupsen/logrus

2 logrus安装

go get安装:

go get github.com/sirupsen/logrus

mod引入:

require github.com/sirupsen/logrus v1.8.1
3 logrus编程入门

特性:
1 完全兼容 golang 标准库日志模块:logrus 拥有六种日志级别:debug、info、warn、error、fatal 和 panic,。
2可扩展的 Hook 机制:允许使用者通过 hook 的方式将日志分发到任意地方,如本地文件系统、标准输出、logstash、elasticsearch或者mq等,或者通过 hook 定义日志内容和格式等.
3 可选的日志输出格式:JSONFormatter和TextFormatter
4 Field机制:通过 Field 机制进行精细化的、结构化的日志记录,而不是通过冗长的消息来记录日志.
5 线程安全

3.1 日志定义不同的级别

第1步:定义全局变量:

var lhLog *logrus.Logger

第2步:初始化lhLog:

func InitLogger() {
	lhLog = logrus.New()
}

第3步:定义不同级别的日志:

func LHDebug(msg string, args ...interface{}) {
	lhLog.Debug(msg, args)
}

func LHInfo(msg string, args ...interface{}) {
	lhLog.Info(msg, args)
}

func LHWarn(msg string, args ...interface{}) {
	lhLog.Warn(msg, args)
}

func LHError(msg string, args ...interface{}) {
	lhLog.Error(msg, args)
}

第4步:测试不同级别的日志:

	fmt.Println("日志级别:")
	lhLog.LHDebug("find a debug...")
	lhLog.LHInfo("find a info message...")
	lhLog.LHWarn("find a warn...")
	lhLog.LHError("find an error...")

测试结果如下:

3.2 日志输出文件名和函数名

特别在系统崩溃时,需要定位到具体的文件名和函数名。
第1步:打开开关:

func SetInfoAddFunctionName(isAdd bool) {
	lhLog.SetReportCaller(isAdd)
}

第2步:测试代码如下:

	fmt.Println("打印文件名和函数名:")
	lhLog.SetInfoAddFunctionName(true)
	lhLog.LHInfo("Stack Overflow...")

测试结果如下:

3.3 日志输出到文件名

第1步:打开开关:

func SetInfoOutputFile(isFile bool) {
	if isFile {
		//log输出到文件
		file, err := os.OpenFile("application.log", os.O_CREATE|os.O_WRONLY, os.ModeAppend)
		if err != nil {
			lhLog.Info("OpenFile fail")
		} else {
			lhLog.Out = file
		}
	} else {
		lhLog.Out = os.Stdout
	}
}

isFile 为true时,输出到file,为false时,输出到标准out。
第2步:测试代码如下:

	fmt.Println("输出到文件:")
	lhLog.SetInfoOutputFile(true)
	lhLog.LHInfo("tack Overflow...")

application.log文件的位置如下:

打开application.log:

3.4 日志格式化输出

如果想增加filed,而且JSON格式化输出,这里以kafka的消息为例进行说明,
第1步:代码:

//使用Fields来进行精细化
func LHKafkaInfo(topic string, msg string, info string) {
	lhLog.Formatter = &logrus.JSONFormatter{}
	lhLog.WithFields(logrus.Fields{
		"topic":   topic,
		"message": msg,
	}).Info(info)
}

第2步:测试代码如下:

	fmt.Println("JSON格式输出:")
	lhLog.LHKafkaInfo("weather", "temperature 26℃","receive a weather message...")

测试结果如下:

3.5 日志切割

日志切割需要借助github.com/lestrrat-go/file-rotatelogs
来实现,主要代码如下:

func Rotate() {
	// 日志文件的位置
	path := "/application.log"
	// 日志切割时间间隔
	duration := time.Duration(60 * time.Second)
	rLog, _ := rotatelogs.New(
		"application"+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(path), // // 指向最新的日志文件
		rotatelogs.WithRotationTime(duration))
	lhLog.SetOutput(rLog)
}

测试代码如下:

fmt.Println("日志切割分离:")
	lhLog.Rotate()
	for {
		lhLog.LHInfo("hello, world!")
		time.Sleep(time.Duration(30) * time.Second)
	}

测试结果如下:

可以看到每分钟都会生成新的日志文件。

代码:
https://gitee.com/linghufeixia/go-simple
chapter4

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995952.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存