英文:
Logrus add extra field to contextlogger
问题
我在所有的Go应用程序中都使用logrus,并最近开始使用上下文日志记录器。现在我想在应用程序的执行路径中“构建”一个上下文。下面的示例说明了我的意图。
package main
import (
"github.com/Sirupsen/logrus"
)
func main() {
logrus.Info("normal logger")
cl := logrus.WithFields(
logrus.Fields{
"extra_field_one": "extra_value_one",
})
// 这里有一些代码
// 在这里,我想向上下文日志记录器cl添加一个额外的字段。我该如何做到这一点?
}
编辑
正如ymonad提到的,可以通过覆盖contextLogger来实现。还发现可以添加一个额外的字段:
cl = cl.WithField("key", "value")
英文:
I use logrus in all my go apps and recently I started using a context logger. Now I want to "build up" a context during the execution path of my app. See example below, which illustrates what I want.
package main
import (
"github.com/Sirupsen/logrus"
)
func main() {
logrus.Info("normal logger")
cl := logrus.WithFields(
logrus.Fields{
"extra_field_one": "extra_value_one",
})
// some code here
// here I want to add an additional field to to contextlogger cl.
// How do I do that?
}
EDIT
As ymonad mentioned, it's possible by overwriting the contextLogger. Also found out that you can add one additional field:
cl = cl.WithField("key", "value")
答案1
得分: 18
你可以直接调用cl.WithFields()
函数。
package main
import "github.com/Sirupsen/logrus"
func main() {
cl := logrus.WithFields(
logrus.Fields{
"extra_field_one": "extra_value_one",
})
cl = cl.WithFields(
logrus.Fields{
"extra_field_two": "extra_value_two",
})
cl.Info("hello world")
}
输出结果为:
INFO[0000] hello world extra_field_one="extra_value_one" extra_field_two="extra_value_two"
英文:
You can just call cl.WithFields()
package main
import "github.com/Sirupsen/logrus"
func main() {
cl := logrus.WithFields(
logrus.Fields{
"extra_field_one": "extra_value_one",
})
cl = cl.WithFields(
logrus.Fields{
"extra_field_two": "extra_value_two",
})
cl.Info("hello world")
}
Output is:
INFO[0000] hello world extra_field_one="extra_value_one" extra_field_two="extra_value_two"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论