logrus自定义日志输出格式

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数据均没有输出。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值