英文:
Set nested fields in Golang with the Logrus?
问题
我正在使用github.com/sirupsen/logrus
创建一个日志记录器。这简化了在日志记录器中初始化字段的过程(根据文档很直观):
package main
import "github.com/sirupsen/logrus"
func main() {
logFields := logrus.Fields{
"details": logrus.Fields{
"app_name": "Some name",
"app_version": "Some version",
},
}
logger := logrus.New()
logger.WithFields(logFields)
}
这个库似乎只允许在顶层使用WithFields
方法添加字段(就像最后一行那样)。
但是因为我的 API 有很多步骤,我需要在每个步骤下添加details
下的嵌套字段(以累积日志数据),然后在最后一起输出。
我该如何添加这些字段呢?
英文:
I'm using github.com/sirupsen/logrus
to make a logger. This simplifies how fields are being initiated in the logger (straightforward from docs):
package main
import "github.com/sirupsen/logrus"
func main() {
logFields := logrus.Fields{
"details": logrus.Fields{
"app_name": "Some name",
"app_version": "Some version",
},
}
logger := logrus.New()
logger.WithFields(logFields)
}
The library seems to allow to add fields with method WithFields
only at top level (as in the last line).
But because my API has many steps, I need to add nested fields under details
with every step (to accumulate log data), then output it all together in the end.
How can I add these fields?
答案1
得分: 2
logrus.Fields
只是map[string]interface{}
,所以你可以将每个步骤中的所有数据嵌套到一个结构体中,例如:
type Details struct {
Step1 string `json:"step1"`
Step2 string `json:"step2"`
Step3 string `json:"step3"`
}
最后使用logger.WithFields(logFields).Debugln("some debug info")
。
另一种方法是,你可以创建多个变量来保存每个步骤的数据,例如:
var step1data = "step1"
var step2data = "step2"
最后使用:
logger.WithFields(logrus.Fields{
"details": logrus.Fields{
"step1": step1data,
"step2": step2data,
},
}).Debugln("some debug info")
英文:
logrus.Fields
is just map[string]interface{}
, so you can nest all data in every steps into a struct like
type Details struct {
Step1 string `json:"step1"`
Step2 string `json:"step2"`
Step3 string `json:"step3"`
}
and finally logger.WithFields(logFields).Debugln("some debug info")
Another method, you can create multiple variables to save data from every step, for example
var step1data = "step1"
var step2data = "step2"
and finally
logger.WithFields(logrus.Fields{
"details": logrus.Fields{
"step1": step1data,
"step2": step2data,
},
}).Debugln("some debug info")`
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论