6

Golang一日一库之logrus - 始識

 1 year ago
source link: https://www.cnblogs.com/zichliang/p/17325328.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

之前一篇文章介绍了 日志库zap https://www.cnblogs.com/zichliang/p/17311480.html
毋庸置疑,zap库无论是Golang在项目中 还是生产中都极其优秀的一个数据库,而且他是当今Go最快的日志库 性能最高的日志库。
但是今天缺不是来说他的,今天介绍的是另一款日志库 logrus
虽然 logrus 已经不维护 且不更新,但是个人感觉logrus比zap 要好用很多,不是说性能,是使用的简易程度而言。

logrus介绍

首先贴上github 地址:

https://github.com/sirupsen/logrus

logrus相比较zap 没有完整的日志库级别 但是比起自带的logger还是要丰富很多
一共有七种日志库级别 Trace, Debug, Info, Warning, Error, Fatal, Panic。

性能:相别zap 略逊一筹

结构化而言:日期时间,级别,信息

而他的优缺点则更为明显:

  • 优点在一开始也提及了 就是使用非常简单。
  • 缺点也更加显而易见 性能一般,日志库等级不丰富(其实七个日库等级 一般而言也够用。)
go get -u github.com/sirupsen/logrus

点击展开

package test import ( "github.com/sirupsen/logrus" "os" "testing") func init() { logrus.SetReportCaller(false) logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.SetOutput(os.Stdout) logrus.SetLevel(logrus.WarnLevel)} func TestLog(t *testing.T) { //time="2023-04-17T11:06:36+08:00" level=info msg="hello,world" 用户= "创建时的日志" // WithFields从标准记录器创建一个条目,并向其添加多个字段。这只是一个' WithField '的助手,为每个字段调用它一次。注意,它不会记录,直到你调用调试,打印,信息,警告,致命或恐慌的条目返回。 logger := logrus.WithFields(logrus.Fields{ "用户": "创建时的日志", }) logger.Info("hello,world")}

WithFields

WithFields从标准记录器创建一个条目,并向其添加多个字段。
这只是一个' WithField '的助手,为每个字段调用它一次。注意,它不会记录,直到你调用调试,打印,信息,警告,等条目返回。
可以随意调用

点击展开

logger := logrus.WithFields(logrus.Fields{ "用户": "创建时的日志",})logger.Trace("Trace 级别的信息")logger.Info("Info 级别的信息")logger.Debug("Debug 级别的信息") logrus.Warn("Warn 级别的信息")logrus.Error("Error 级别的信息")logrus.Fatal("Fatal 级别的信息")logrus.Panic("Panic 级别的信息") // 会报错

SetReportCaller

至于 logrus.SetReportCaller(true)
我们直接看结果

logrus.SetReportCaller(true)// time="2023-04-17T11:06:52+08:00" level=info msg="hello,world" func=DoubleCarbon/test.TestLog file="E:/Golang/DoubleCarbon/test/log_test.go:16" 用 户="创建时的日志"
logrus.SetReportCaller(false)// time="2023-04-17T11:06:36+08:00" level=info msg="hello,world" 用户= "创建时的日志"

SetFormatter

SetFormatter设置标准记录器格式化程序。
以 JSON 格式而不是默认的 ASCII 格式化程序记录。

SetOutput

输出到标准输出而不是默认标准输出
可以是任何io编写器
这里我写的输出到 终端中 也可以输出到文件中

SetLevel

仅记录警告严重性或更高级别。
可以任意定义。一般都是定义debug 以上级别的
不然日志太多就没有意义了。

Hooks

https://github.com/sirupsen/logrus/wiki/Hooks
使用上面这些库 包含了可以所有可以连接logrus的hooks

2721529-20230417151308652-1687866604.png

因为一般来说要发送日志 肯定不可能选择 MySQL这种数据库 ,因为日志运行起来量是很大的,所以一般来说
会选择 es 或者redis 或者mongodb 这种非关系数据库。
这里就简单举个redis的例子

logrus-redis-hook

go get github.com/rogierlommers/logrus-redis-hook

点击展开

package main import ( logredis "github.com/rogierlommers/logrus-redis-hook" "io/ioutil" "github.com/sirupsen/logrus") func init() { hookConfig := logredis.HookConfig{ Host: "localhost", Key: "my_redis_key", Format: "v0", App: "my_app_name", Port: 6379, Hostname: "my_app_hostname", // will be sent to field @source_host DB: 0, // optional TTL: 3600, Password: "*****", // 写你的密码 } hook, err := logredis.NewHook(hookConfig) if err == nil { logrus.AddHook(hook) } else { logrus.Errorf("logredis error: %q", err) }} func main() { // when hook is injected succesfully, logs will be sent to redis server logrus.Info("just some info logging...") // we also support log.WithFields() logrus.WithFields(logrus.Fields{ "animal": "walrus", "foo": "bar", "this": "that"}). Info("additional fields are being logged as well") // If you want to disable writing to stdout, use setOutput logrus.SetOutput(ioutil.Discard) logrus.Info("This will only be sent to Redis")}

如图所示

2721529-20230417152108591-1545690759.png

直接就在redis里写入了日志信息

如果失败 如下图所示

2721529-20230417152246149-603863432.png

gin框架使用logrus

直接看官方文档把

点击展开

// a gin with logrus demo var log = logrus.New() func init() { // Log as JSON instead of the default ASCII formatter. log.Formatter = &logrus.JSONFormatter{} // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example f, _ := os.Create("./gin.log") log.Out = f gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = log.Out // Only log the warning severity or above. log.Level = logrus.InfoLevel} func main() { // 创建一个默认的路由引擎 r := gin.Default() // GET:请求方式;/hello:请求的路径 // 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数 r.GET("/hello", func(c *gin.Context) { log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Warn("A group of walrus emerges from the ocean") // c.JSON:返回JSON格式的数据 c.JSON(200, gin.H{ "message": "Hello world!", }) }) // 启动HTTP服务,默认在0.0.0.0:8080启动服务 r.Run()}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK