在日志记录中使用struct代替map



我使用logus包在Go项目中进行日志记录。为了在日志中显示键值对,文档给出了以下格式:

log.WithFields(log.Fields{
"animal": "walrus",
"size":   10,
}).Info("A group of walrus emerges from the ocean")

我希望在所有日志中使用一个通用的结构,而不是在每个日志中手动使用字符串键(以避免键输入错误)。

像这样:

type LogMessage struct {
Status  bool        `json:"status"`
Message string      `json:"message"`
}
log.WithFields(&LogMessage {Status: false, Message: "Error User Already Exists"}).Info("User Creation Failed.")

日志输出如下:

time="2015-03-26T01:27:38-04:00" level=info msg="User Creation Failed." status=false message="Error User Already Exists"

如何实现?

感谢您的帮助!

不能将结构体传递给WithFields()。它采用Fields类型(基本上是map[string]interface{})。为了避免在常见的键名上犯错误,你可以创建常量——这样,如果你在常量名代码中犯了错别字,甚至不会编译(最后,它比传递一个结构体更容易编写):

const Status = "status"
const Message = "message"
//...
log.WithFields(log.Fields{Status: true, Message: "a message"}).Info("foo")

要实现您想要的,您需要在传递给WithFields()之前将struct转换为映射:

import (
structs "github.com/fatih/structs" // ARCHIVED
log "github.com/sirupsen/logrus"
)
//...

type LogMessage struct {
Status  bool        `json:"status"`
Message string      `json:"message"`
}
log.WithFields(structs.Map(&LogMessage{Status: true, Message: "a message"})).Info("foo")
// Will output:
// time="2009-11-10T23:00:00Z" level=info msg=foo Message="a message" Status=true

(注意:我使用了库结构体"将其存档只是为了演示原则。此外,需要进行转换的反射会增加性能成本,所以我不会在程序的性能关键部分使用它)。

你可以使用一个自定义的换行函数,在里面你可以设置你的字段键。

https://play.golang.org/p/H22M63kn8Jb

package main
import (
log "github.com/sirupsen/logrus"
)
func LogMyMessages(messageStruct *myMessageStruct) {
log.WithFields(log.Fields{"status": messageStruct.Status, "message": messageStruct.Message}).Info("foo")
}
type myMessageStruct struct {
Message string
Status  bool
}
func main() {
LogMyMessages(&myMessageStruct{Status: true, Message: "test message"})
}

给出如下信息

时间="2009 - 11 - 10 - t23:00:00z"Level =info msg=foo message= test message"状态= true

不完全是您需要的,只是想使用fmt提供另一个选项。

log.WithFields(log.Fields{
"info": fmt.Sprintf("%+v", LogMessage{Status: false, Message: "Error User Already Exists"}),
}).Info("User Creation Failed.")

这将产生如下内容

time="2015-03-26T01:27:38-04:00" level=info msg="User Creation Failed." info="{Status:false Message:'Error User Already Exists'}"

最新更新