3 回答

TA貢獻1851條經驗 獲得超4個贊
不完全是你需要的,但只是想使用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'}"

TA貢獻1816條經驗 獲得超6個贊
您可以使用自定義包裝函數,您可以在其中設置字段鍵。
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"})
}
給出這樣的消息
time=“2009-11-10T23:00:00Z” 級別=信息消息=foo 消息=“測試消息”狀態=真

TA貢獻1835條經驗 獲得超7個贊
不能將結構傳遞給 。它需要類型(基本上是)。為了避免在常用鍵名稱中出錯,您可以創建常量 - 這樣,如果您在常量名稱中輸入拼寫錯誤,代碼甚至不會編譯(最終編寫起來會比傳遞結構更不詳細):WithFields()Fieldsmap[string]interface{}
const Status = "status"
const Message = "message"
//...
log.WithFields(log.Fields{Status: true, Message: "a message"}).Info("foo")
要實現您想要的精確內容,您需要在傳遞到 之前將結構轉換為映射:WithFields()
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
(注意:我使用了存檔的庫“結構”來演示原理。此外,進行轉換所需的反射會增加性能成本,因此我不會在程序的性能關鍵部分使用它)。
- 3 回答
- 0 關注
- 100 瀏覽
添加回答
舉報