Set nested fields in Golang with the Logrus?

huangapple go评论70阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2021年8月19日 07:22:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/68840336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定