golang学习笔记 ---日志库 logrus

logrus特性

官方自己宣传的最大亮点是 结构化。

  • 完全兼容golang标准库日志模块:logrus拥有六种日志级别:debug、info、warn、error、fatal和panic,这是golang标准库日志模块的API的超集.如果您的项目使用标准库日志模块,完全可以以最低的代价迁移到logrus

    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 机制进行精细化的、结构化的日志记录,而不是通过冗长的消息来记录日志.

golang logrus的GitHub地址

           logrus的GitHub地址    https://github.com/sirupsen/logrus

           lfshook的GitHub地址    https://github.com/rifflock/lfshook

           file-rotatelogs的GitHub地址   https://github.com/lestrrat-go/file-rotatelogs

           pkg/errors的GitHub地址    https://github.com/pkg/errors   

logrus 的使用

package main

import (
    log "github.com/sirupsen/logrus" //这个日志依赖库,需要使用
    //govendor fetch github.com/sirupsen/logrus 下载到vendor目录。
)

func main() {
    log.WithFields(log.Fields{
        "info": "这是golang日志框架--logrus",
    }).Info("描述信息为golang日志框架logrus的学习")
}

设置日志输出格式,日志级别等信息

package main

import (
    "os"

    log "github.com/sirupsen/logrus"
)

func initLog() {
    log.SetFormatter(&log.JSONFormatter{}) //设置日志的输出格式为json格式,还可以设置为text格式
    log.SetOutput(os.Stdout)               //设置日志的输出为标准输出
    log.SetLevel(log.InfoLevel)            //设置日志的显示级别,这一级别以及更高级别的日志信息将会输出
}

func main() {
    //以package级别方式使用日志
    initLog()
    log.WithFields(log.Fields{
        "info": "这是golang日志框架--logrus",
    }).Info("描述信息为golang日志框架logrus的学习")

    log.WithFields(log.Fields{
        "omg":     true,
        "number":  122,
        "country": "china",
    }).Warn("hello this is warn level") //警告级别

    log.WithFields(log.Fields{
        "hello": "jason",
    }).Fatal("the ice breaks!") //最高级别,致命信息

}

使用日志实例的方式使用日志

原文地址:https://www.cnblogs.com/saryli/p/13398082.html