1. 简介
golang标准库的日志框架非常简单,仅仅提供了print,panic和fatal三个函数对于更精细的日志级别、日志文件分割以及日志分发等方面并没有提供支持. 所以催生了很多第三方的日志库,但是在golang的世界里,没有一个日志库像slf4j那样在Java中具有绝对统治地位.golang中,流行的日志框架包括logrus、zap、zerolog、seelog等.
logrus是目前Github上star数量最多的日志库,目前(2022.04)star数量为20.3k,fork数为2.1k. logrus功能强大,性能高效,而且具有高度灵活性,提供了自定义插件的功能.很多开源项目,如docker,prometheus,dejavuzhou/ginbro等,都是用了logrus来记录其日志.
2. 配置
日志级别: logrus有7个日志级别,依次是Trace << Debug << Info << Warning << Error << Fatal << Panic
logrus.SetLevel(logrus.DebugLevel) //只输出不低于当前级别的日志数据
日志格式: logrus内置了JSONFormatter和TextFormatter两种格式,也可以通过Formatter接口定义日志格式
//json格式输出
logrus.SetFormatter(&logrus.JSONFormatter{
PrettyPrint: true,
TimestampFormat: "2018-01-02 15:04:05",
})
//输出结果
{
"file": "/home/mv-user/RimeData/script/cmd/request.go:20",
"func": "main.main",
"level": "info",
"msg": "我执行了!",
"time": "18048-04-18 10:32:05"
}
//文本格式输出
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
EnvironmentOverrideColors: true,
TimestampFormat: "2018-01-02 15:04:05",
})
//输出结果
[36mINFO[0m[0000]/home/mv-user/RimeData/script/cmd/request.go:21 main.main() 我执行了!
日志输出:
logfile, _ := os.OpenFile("./app.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
logrus.SetOutput(logfile)
logrus.SetReportCaller(true) //定位行号
3. 日志打印
FieldLogger接口: FieldLogger定义了所有日志打印的方法
type FieldLogger interface {
WithField(key string, value interface{}) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Printf(format string, args ...interface{})
Warnf(format string, args ...interface{})
Warningf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
Debug(args ...interface{})
Info(args ...interface{})
Print(args ...interface{})
Warn(args ...interface{})
Warning(args ...interface{})
Error(args ...interface{})
Fatal(args ...interface{})
Panic(args ...interface{})
Debugln(args ...interface{})
Infoln(args ...interface{})
Println(args ...interface{})
Warnln(args ...interface{})
Warningln(args ...interface{})
Errorln(args ...interface{})
Fatalln(args ...interface{})
Panicln(args ...interface{})
// IsDebugEnabled() bool
// IsInfoEnabled() bool
// IsWarnEnabled() bool
// IsErrorEnabled() bool
// IsFatalEnabled() bool
// IsPanicEnabled() bool
}
日志打印1:默认实例 (函数),即通过logrus包提供的函数(覆盖了FieldLogger接口的所有方法),直接打印日志。但其实logrus包函数是调用了logrus.Loger默认实例。
logrus.Infoln("我执行了!")
logrus.Errorf("报错了!")
日志打印2:Logger实例(对象),它实现了FieldLogger接口。
logger := logrus.New()
logger.SetLevel(logrus.DebugLevel)
logger.SetFormatter(&logrus.JSONFormatter{
PrettyPrint: true,
TimestampFormat: "2018-01-02 15:04:05",
})
logfile, _ := os.OpenFile("./app.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
logger.SetOutput(logfile)
logger.SetReportCaller(true)
logger.Infoln("我执行了!")
logger.Errorf("报错了")
日志打印3:Entry示例(对象),它也实现了FieldLogger接口,是最终是日志打印入口。
- 这里用到了Field机制,logrus鼓励通过Field机制进行精细化的、结构化的日志记录,而不是通过冗长的消息来记录日志。