go日志库logrus如何安装及使用

发布时间:2022-08-04 10:33:00 作者:iii
来源:亿速云 阅读:138

这篇文章主要介绍“go日志库logrus如何安装及使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“go日志库logrus如何安装及使用”文章能帮助大家解决问题。

安装简介

Logrus是Go的结构化日志记录器,与标准的日志记录器库完全API兼容。

go get安装的logrus库

 go get github.com/sirupsen/logrus

快速使用

package main
import (
   log "github.com/sirupsen/logrus"
)
func main() {
   log.SetLevel(log.TraceLevel)
   log.Trace("trace")
   log.Debug("debug")
   log.Info("info")
   log.Warn("warn")
   log.Error("error")
   log.Fatal("fatal")
   log.Panic("panic")
}

输出:

TRAC[0000] trace                                        
DEBU[0000] debug                                        
INFO[0000] info                                         
WARN[0000] warn                                         
ERRO[0000] error                                        
FATA[0000] fatal                                        
exit status 1

可以看到panic没有输出,因为fatal会导致goroutine直接退出。

支持的日志级别

logrus支持多种日志级别,下面从小到大:

可以看到Trace级别最大,Panic最小。默认的级别为Info,高于这个级别的日志不会输出。

日期

可以看到上面的日志没有时间,可以指定日志格式:

package main
import (
   log "github.com/sirupsen/logrus"
)
func main() {
   log.SetLevel(log.TraceLevel)
   log.SetFormatter(&log.TextFormatter{
      FullTimestamp:   true,
      TimestampFormat: "2022-07-17 00:00:00.000",
   })
   log.Trace("trace")
   log.Debug("debug")
   log.Info("info")
   log.Warn("warn")
   log.Error("error")
   log.Fatal("fatal")
   log.Panic("panic")
}

精确到毫秒。

输出:

TRAC[171717+08-77 00:00:00.628] trace                                        
DEBU[171717+08-77 00:00:00.629] debug                                        
INFO[171717+08-77 00:00:00.629] info                                         
WARN[171717+08-77 00:00:00.629] warn                                         
ERRO[171717+08-77 00:00:00.629] error                                        
FATA[171717+08-77 00:00:00.629] fatal                                        
exit status 1

打印调用位置

在进行定位的时候需要知道是那行代码调用的log.SetReportCaller(true)

package main
import (
   log "github.com/sirupsen/logrus"
)
func main() {
   log.SetLevel(log.TraceLevel)
   log.SetReportCaller(true)
   log.SetFormatter(&log.TextFormatter{
      FullTimestamp:   true,
      TimestampFormat: "2022-07-17 00:00:00.000",
   })
   log.Trace("trace")
   log.Debug("debug")
   log.Info("info")
   log.Warn("warn")
   log.Error("error")
   log.Fatal("fatal")
   log.Panic("panic")
}

输出:

TRAC[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:14 main.main() trace                                        
DEBU[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:15 main.main() debug                                        
INFO[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:16 main.main() info                                         
WARN[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:17 main.main() warn                                         
ERRO[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:18 main.main() error                                        
FATA[171717+08-77 00:00:00.019]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:19 main.main() fatal                                        
exit status 1

添加字段

定位问题需要知道具体是那个数据调用的,可以借助于log.WithFieldlog.WithFieldslog.WithField内部调用的也是log.WithFields,参数底层使用map[string]interface{}数据结构保存:

package main
import (
   log "github.com/sirupsen/logrus"
   "os"
)
func main() {
   log.SetLevel(log.TraceLevel)
   log.SetReportCaller(true)
   log.SetFormatter(&log.TextFormatter{
      FullTimestamp:   true,
      TimestampFormat: "2022-07-17 00:00:00.000",
   })
   id := os.Args[1]
   mylog := log.WithField("id", id)
   mylog.Trace("trace")
   mylog.Debug("debug")
   mylog.Info("info")
   mylog.Warn("warn")
   mylog.Error("error")
   mylog.Fatal("fatal")
   mylog.Panic("panic")
}

输出:

➜  StudyProject go run  src/log/my_log.go 123
TRAC[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:22 main.main() trace                                         id=123
DEBU[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:23 main.main() debug                                         id=123
INFO[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:24 main.main() info                                          id=123
WARN[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:25 main.main() warn                                          id=123
ERRO[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:26 main.main() error                                         id=123
FATA[171717+08-77 00:00:00.665]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:27 main.main() fatal                                         id=123
exit status 1

给字段值加引号

配置ForceQuotetrue

package main
import (
   log "github.com/sirupsen/logrus"
   "os"
)
func main() {
   log.SetLevel(log.TraceLevel)
   log.SetReportCaller(true)
   log.SetFormatter(&log.TextFormatter{
      FullTimestamp:   true,
      TimestampFormat: "2022-07-17 00:00:00.000",
      ForceQuote:      true,
   })
   id := os.Args[1]
   mylog := log.WithField("id", id)
   mylog.Trace("trace")
   mylog.Debug("debug")
   mylog.Info("info")
   mylog.Warn("warn")
   mylog.Error("error")
   mylog.Fatal("fatal")
   mylog.Panic("panic")
}

输出:

➜  StudyProject go run  src/log/my_log.go 123
TRAC[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:22 main.main() trace                                         id="123"
DEBU[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:23 main.main() debug                                         id="123"
INFO[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:24 main.main() info                                          id="123"
WARN[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:25 main.main() warn                                          id="123"
ERRO[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:26 main.main() error                                         id="123"
FATA[171717+08-77 00:00:00.427]/Users/wanghaifeng/GolandProjects/StudyProject/src/log/my_log.go:27 main.main() fatal                                         id="123"
exit status 1

设置钩子

每条日志在输出前都会执行钩子的特定方法,相当于全局拦截,可以方便做一些扩展,比如添加字段channel表明日志是那个应用输出的、增加tranceid方便对问题的跟踪、输出日志文件等。

设置channel

package hooks
import log "github.com/sirupsen/logrus"
type ChannelHook struct {
   ChannelName string
}
func (h ChannelHook) Levels() []log.Level {
   return log.AllLevels
}
func (h ChannelHook) Fire(entry *log.Entry) error {
   entry.Data["channel"] = h.ChannelName
   return nil
}
package main
import (
   logs "StudyProject/src/log/hooks"
   log "github.com/sirupsen/logrus"
)
func main() {
   log.AddHook(logs.ChannelHook{
      ChannelName: "web",
   })
   log.Info("info")
}

输出:

INFO[0000] info                                          channel=web

输出日志

可以利用logrus的hook自己写入文件,但是指定单个文件收集的时间范围、保存的时间logrus并不支持,笔者目前的项目使用的是file-rotatelogs,但是作者已经不更新和维护,所以这里就不使用它来展示,有在考虑使用goframe的glog替换。

笔者这里就写个简单例子演示如何利用logrus的hook去写文件并且把控制台的打印干掉:

package hooks
import (
   log "github.com/sirupsen/logrus"
   "io/ioutil"
)
//
//FileHook
//  @Description: 文件hook
//
type FileHook struct {
   //
   //  FileName
   //  @Description:  文件名
   //
   FileName string
}
func (h FileHook) Levels() []log.Level {
   return log.AllLevels
}
func (h FileHook) Fire(entry *log.Entry) error {
   fomat := &log.TextFormatter{
      FullTimestamp:   true,
      TimestampFormat: "2022-07-17 00:00:00.000",
   }
   //  从entry从获得日志内容
   msg, err := fomat.Format(entry)
   if err != nil {
      return err
   }
   err = ioutil.WriteFile(h.FileName, msg, 0644)
   if err != nil {
      return err
   }
   return nil
}
package main
import (
   logs "StudyProject/src/log/hooks"
   log "github.com/sirupsen/logrus"
   "io/ioutil"
)
func main() {
   log.AddHook(logs.FileHook{"log"})
   //  关闭控制台打印
   log.SetOutput(ioutil.Discard)
   log.Info("test log write file")
}

关于“go日志库logrus如何安装及使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

推荐阅读:
  1. Golang logrus 日志包及日志切割的实现
  2. golang日志框架之logrus的使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go logrus

上一篇:在微信小程序中如何获取用户位置

下一篇:JavaScript中的回调函数怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》