侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Golang logrus 日志包及日志切割的实现

Go  /  管理员 发布于 7年前   309

本文主要介绍 Golang 中最佳日志解决方案,包括常用日志包logrus 的基本使用,如何结合file-rotatelogs 包实现日志文件的轮转切割两大话题。

Golang 关于日志处理有很多包可以使用,标准库提供的 log 包功能比较少,不支持日志级别的精确控制,自定义添加日志字段等。在众多的日志包中,更推荐使用第三方的 logrus 包,完全兼容自带的 log 包。logrus 是目前 Github 上 star 数量最多的日志库,logrus 功能强大,性能高效,而且具有高度灵活性,提供了自定义插件的功能。

很多开源项目,如 docker,prometheus,dejavuzhou/ginbro 等,都是用了 logrus 来记录其日志。

logrus 特性

  • 完全兼容 golang 标准库日志模块:logrus 拥有六种日志级别:debug、info、warn、error、fatal 和 panic,这是 golang 标准库日志模块的 API 的超集。
  • logrus.Debug(“Useful debugging information.”)
  • logrus.Info(“Something noteworthy happened!”)
  • logrus.Warn(“You should probably take a look at this.”)
  • logrus.Error(“Something failed but I'm not quitting.”)
  • logrus.Fatal(“Bye.”) //log之后会调用os.Exit(1)
  • logrus.Panic(“I'm bailing.”) //log之后会panic()
  • 可扩展的 Hook 机制:允许使用者通过 hook 的方式将日志分发到任意地方,如本地文件系统、标准输出、logstash、elasticsearch 或者 mq 等,或者通过 hook 定义日志内容和格式等。
  • 可选的日志输出格式:logrus 内置了两种日志格式,JSONFormatter 和 TextFormatter,如果这两个格式不满足需求,可以自己动手实现接口 Formatter 接口来定义自己的日志格式。
  • Field 机制:logrus 鼓励通过 Field 机制进行精细化的、结构化的日志记录,而不是通过冗长的消息来记录日志。
  • logrus 是一个可插拔的、结构化的日志框架。
  • Entry: logrus.WithFields 会自动返回一个 *Entry,Entry里面的有些变量会被自动加上
  • time:entry被创建时的时间戳
  • msg:在调用.Info()等方法时被添加
  • level,当前日志级别

logrus 基本使用

package mainimport (  "os"  "github.com/sirupsen/logrus"  log "github.com/sirupsen/logrus")var logger *logrus.Entryfunc init() {  // 设置日志格式为json格式  log.SetFormatter(&log.JSONFormatter{})  log.SetOutput(os.Stdout)  log.SetLevel(log.InfoLevel)  logger = log.WithFields(log.Fields{"request_id": "123444", "user_ip": "127.0.0.1"})}func main() {  logger.Info("hello, logrus....")  logger.Info("hello, logrus1....")  // log.WithFields(log.Fields{  // "animal": "walrus",  // "size":  10,  // }).Info("A group of walrus emerges from the ocean")  // log.WithFields(log.Fields{  // "omg":  true,  // "number": 122,  // }).Warn("The group's number increased tremendously!")  // log.WithFields(log.Fields{  // "omg":  true,  // "number": 100,  // }).Fatal("The ice breaks!")}

基于 logrus 和 file-rotatelogs 包实现日志切割

很多时候应用会将日志输出到文件系统,对于访问量大的应用来说日志的自动轮转切割管理是个很重要的问题,如果应用不能妥善处理日志管理,那么会带来很多不必要的维护开销:外部工具切割日志、人工清理日志等手段确保不会将磁盘打满。

file-rotatelogs: When you integrate this to to you app, it automatically write to logs that are rotated from within the app: No more disk-full alerts because you forgot to setup logrotate!

logrus 本身不支持日志轮转切割功能,需要配合 file-rotatelogs 包来实现,防止日志打满磁盘。file-rotatelogs 实现了 io.Writer 接口,并且提供了文件的切割功能,其实例可以作为 logrus 的目标输出,两者能无缝集成,这也是 file-rotatelogs 的设计初衷:

It's normally expected that this library is used with some other logging service, such as the built-in log library, or loggers such as github.com/lestrrat-go/apache-logformat.

示例代码:

应用日志文件 /Users/opensource/test/go.log,每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。

package mainimport ( "time" rotatelogs "github.com/lestrrat-go/file-rotatelogs" log "github.com/sirupsen/logrus")func init() { path := "/Users/opensource/test/go.log" /* 日志轮转相关函数 `WithLinkName` 为最新的日志建立软连接 `WithRotationTime` 设置日志分割的时间,隔多久分割一次 WithMaxAge 和 WithRotationCount二者只能设置一个  `WithMaxAge` 设置文件清理前的最长保存时间  `WithRotationCount` 设置文件清理前最多保存的个数 */ // 下面配置日志每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。 writer, _ := rotatelogs.New( path+".%Y%m%d%H%M", rotatelogs.WithLinkName(path), rotatelogs.WithMaxAge(time.Duration(180)*time.Second), rotatelogs.WithRotationTime(time.Duration(60)*time.Second), ) log.SetOutput(writer) //log.SetFormatter(&log.JSONFormatter{})}func main() { for { log.Info("hello, world!") time.Sleep(time.Duration(2) * time.Second) }}

Golang 标准日志库 log 使用

虽然 Golang 标准日志库功能少,但是可以选择性的了解下,下面为基本使用的代码示例,比较简单:

package mainimport (  "fmt"  "log")func init() {  log.SetPrefix("【UserCenter】")  // 设置每行日志的前缀  log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC) // 设置日志的抬头字段}func main() {  log.Println("log...")  log.Fatalln("Fatal Error...")  fmt.Println("Not print!")}

自定义日志输出

package mainimport (  "io"  "log"  "os")var (  Info  *log.Logger  Warning *log.Logger  Error  *log.Logger)func init() {  errFile, err := os.OpenFile("errors.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)  if err != nil {    log.Fatalln("打开日志文件失败:", err)  }  Info = log.New(os.Stdout, "Info:", log.Ldate|log.Ltime|log.Lshortfile)  Warning = log.New(os.Stdout, "Warning:", log.Ldate|log.Ltime|log.Lshortfile)  Error = log.New(io.MultiWriter(os.Stderr, errFile), "Error:", log.Ldate|log.Ltime|log.Lshortfile)}func main() {  Info.Println("Info log...")  Warning.Printf("Warning log...")  Error.Println("Error log...")}

相关文档

https://mojotv.cn/2018/12/27/golang-logrus-tutorial
https://github.com/lestrrat-go/file-rotatelogs
https://www.flysnow.org/2017/05/06/go-in-action-go-log.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Golang执行go get私有库提示"410 Gone" 的问题及解决办法
    下一条:
    Golang 实现插入排序的方法示例(2种)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客