美文网首页
logrus自定义日志输出格式

logrus自定义日志输出格式

作者: 跑马溜溜的球 | 来源:发表于2021-05-11 14:21 被阅读0次

1. 设置日志格式的方法

logrus中,使用如下方法设置日志格式

func SetFormatter(formatter Formatter) 

其中Formatter是一个接口

type Formatter interface {
    Format(*Entry) ([]byte, error)
}

所以,实现自定义日志格式,本质上就是实现Formatter接口,然后通过SetFormatter方式将其告知logrus。

2. 已有Formatter

logrus包中自带两种Formatter,分别是TextFormatter和JSONFormatter。 默认情况下,使用TextFormatter输出。

func main(){
    logrus.WithField("name", "ball").Info("this is from logrus")
}

//输出
INFO[0000] this is from logrus      name=ball

说明:

  • 以上是go version go1.14.4 linux/amd64环境的输出。
    go version go1.14.4 windows/amd64中的输出较为友好:
time="2021-05-10T15:54:33+08:00" level=info msg="this is from logrus" name=ball

  • 下文输出均以go version go1.14.4 linux/amd64为准。

2.1 TextFormatter

TextFormatter有若干可定制参数,常用参数如下,更多参数及功能,可在源码的text_formatter.go中看到。

type TextFormatter struct{
    //颜色显示相关
    ForceColors bool
    EnvironmentOverrideColors bool
    DisableColors bool
    
    //日志中的键值对加引号相关
    ForceQuote bool
    DisableQuote bool
    QuoteEmptyFields bool
    
    //时间戳相关
    DisableTimestamp bool
    FullTimestamp bool
    TimestampFormat string
}

例1

func main(){
    logrus.SetFormatter(&logrus.TextFormatter{
        ForceQuote:true,    //键值对加引号
        TimestampFormat:"2006-01-02 15:04:05",  //时间格式
        FullTimestamp:true,     
    })
    
    logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
}

// 输出
INFO[2021-05-10 16:28:50] info log      name="ball" say="hi"

说明:
默认是Colors模式,该模式下,必须设置FullTimestamp:true, 否则时间显示不生效。

例2

func main(){
    logrus.SetFormatter(&logrus.TextFormatter{
        DisableColors:true,
        ForceQuote:false,
        TimestampFormat:"2006-01-02 15:04:05",
    })
    logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
}

//输出
time="2021-05-10 16:32:42" level=info msg="info log" name=ball say=hi

说明:
DisableColors为true时,日志的样子有所改变。

2.2 JSONFormatter

常用参数如下,更多参数及功能,可在源码的json_formatter.go中看到。

type JSONFormatter struct {
    //时间戳相关
    TimestampFormat string
    DisableTimestamp bool

    DisableHTMLEscape bool

    // PrettyPrint will indent all json logs
    PrettyPrint bool
}

func main(){
    logrus.SetFormatter(&logrus.JSONFormatter{
        TimestampFormat:"2006-01-02 15:04:05",
        PrettyPrint: true,
    })
    logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
}

//输出
{
  "level": "info",
  "msg": "info log",
  "name": "ball",
  "say": "hi",
  "time": "2021-05-10 16:36:05"
}

说明:
若不设置PrettyPrint: true, 则json为单行输出。

3. 自定义Formatter

自定义Formatter,其实就是实现Formatter接口。

type Formatter interface {
    Format(*Entry) ([]byte, error)
}

接口的返回值[]byte,即为输出串。关键在于搞懂输入参数Entry。

3.1 Entry参数

type Entry struct {
    // Contains all the fields set by the user.
    Data Fields

    // Time at which the log entry was created
    Time time.Time

    // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
    Level Level

    //Calling method, with package name
    Caller *runtime.Frame

    //Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
    Message string

    //When formatter is called in entry.log(), a Buffer may be set to entry
    Buffer *bytes.Buffer
}

说明:

type MyFormatter struct {

}

func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error){
    var b *bytes.Buffer
    if entry.Buffer != nil {
        b = entry.Buffer
    } else {
        b = &bytes.Buffer{}
    }

    timestamp := entry.Time.Format("2006-01-02 15:04:05")
    var newLog string
    newLog = fmt.Sprintf("[%s] [%s] %s\n", timestamp, entry.Level, entry.Message)

    b.WriteString(newLog)
    return b.Bytes(), nil
}

func main(){
    logrus.SetFormatter(&MyFormatter{})
    logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
}

//输出
[2021-05-10 17:26:06] [info] info log

说明:例子中没有处理entry.Data的数据,因此使用WithField设置的name,say数据均没有输出。

相关文章

  • Logrus的使用

    Logrus的使用 1、安装 2、Logrus特性 3、log参数配置,定义输出、格式或者日志级别等 4、常规使用...

  • logrus自定义日志输出格式

    1. 设置日志格式的方法 logrus中,使用如下方法设置日志格式 其中Formatter是一个接口 所以,实现自...

  • golang常用代码片段--定制化log组件

    使用logrus配合file-rotatelogs、lfshook实现:1 日志文件按时间切割2 根据日志等级输出...

  • 使用logrus记录gorm sql

    gorm可以方便的输出执行的sql或慢查询。logrus是常用的日志组件,如何将gorm输出的sql通过logru...

  • 基于logrus 的日志分割与自动清理

    因为logrus[https://github.com/Sirupsen/logrus]原生不支持日志分割和自动清...

  • GO Log统一接口

    一、问题 go日志库有很多:zap、 Logrus等,它们没有统一的接口。作为中间件提供方,中间件的日志怎么输出到...

  • 0010.SpringDoc-Openapi Swagger相关

    1.自定义Map类型的输出格式 配置输出格式 在Control中使用 2.自定义LocalDateTime类型输出...

  • Logrus Hook

    问题:在用golang的Logrus库的时候,用Json格式记录日志,有时候希望加一些固定的Fields,比如在日...

  • CocoaLumberjack源码分析

    1.使用 自定义custom context,自定义flag 自定义日志的格式 自定义日志级别,取消DDLog实现...

  • Spring Boot 默认日志配置

    springboot 默认日志配置 SpringBoot 日志配置 默认采用LogBack作为日志输出! 日志格式...

网友评论

      本文标题:logrus自定义日志输出格式

      本文链接:https://www.haomeiwen.com/subject/napgdltx.html