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支持多种日志级别,下面从小到大:

  • Panic:记录日志,然后panic
  • Fatal:致命错误,输出日志后,程序退出
  • Error:错误
  • Warn:警告
  • Info:关键信息
  • Debug:调试信息
  • Trace:很细粒度的信息,一般用不到。

可以看到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")
}

很显然这只是个例子,不可应用于生产。

我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿

猜你喜欢

转载自juejin.im/post/7126102527459721246
今日推荐