前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >logrus自定义日志输出格式

logrus自定义日志输出格式

作者头像
跑马溜溜的球
发布2021-06-01 15:32:03
6.4K0
发布2021-06-01 15:32:03
举报
文章被收录于专栏:日积月累1024日积月累1024

1. 设置日志格式的方法

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

代码语言:javascript
复制
func SetFormatter(formatter Formatter) 

其中Formatter是一个接口

代码语言:javascript
复制
type Formatter interface {
	Format(*Entry) ([]byte, error)
}

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

2. 已有Formatter

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

代码语言:javascript
复制
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中的输出较为友好:
代码语言:javascript
复制
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中看到。

代码语言:javascript
复制
type TextFormatter struct{
    //颜色显示相关
    ForceColors bool
    EnvironmentOverrideColors bool
    DisableColors bool
    
    //日志中的键值对加引号相关
    ForceQuote bool
    DisableQuote bool
    QuoteEmptyFields bool
    
    //时间戳相关
    DisableTimestamp bool
    FullTimestamp bool
    TimestampFormat string
}
例1
代码语言:javascript
复制
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
代码语言:javascript
复制
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中看到。

代码语言:javascript
复制
type JSONFormatter struct {
    //时间戳相关
	TimestampFormat string
	DisableTimestamp bool

	DisableHTMLEscape bool

	// PrettyPrint will indent all json logs
	PrettyPrint bool
}
代码语言:javascript
复制
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接口。

代码语言:javascript
复制
type Formatter interface {
	Format(*Entry) ([]byte, error)
}

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

3.1 Entry参数

代码语言:javascript
复制
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
}

说明:

代码语言:javascript
复制
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数据均没有输出。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/05/11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 设置日志格式的方法
  • 2. 已有Formatter
    • 2.1 TextFormatter
      • 2.2 JSONFormatter
      • 3. 自定义Formatter
        • 3.1 Entry参数
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档