当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Golang logrus 日志包及日志切割的实现

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

2020年05月13日  | 移动技术网IT编程  | 我要评论

小儿偏食,吴曼殊,铜陵学院体育部

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

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 main

import (
  "os"

  "github.com/sirupsen/logrus"
  log "github.com/sirupsen/logrus"
)

var logger *logrus.entry

func 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!

本身不支持日志轮转切割功能,需要配合 包来实现,防止日志打满磁盘。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 main

import (
 "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 main

import (
  "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 main

import (
  "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...")
}

相关文档



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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网