Logrus向上下文记录器添加额外字段

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

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"

huangapple
  • 本文由 发表于 2017年3月21日 15:23:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42920666.html
匿名

发表评论

匿名网友

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

确定