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

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

Logrus add extra field to contextlogger

问题

我在所有的Go应用程序中都使用logrus,并最近开始使用上下文日志记录器。现在我想在应用程序的执行路径中“构建”一个上下文。下面的示例说明了我的意图。

  1. package main
  2. import (
  3. "github.com/Sirupsen/logrus"
  4. )
  5. func main() {
  6. logrus.Info("normal logger")
  7. cl := logrus.WithFields(
  8. logrus.Fields{
  9. "extra_field_one": "extra_value_one",
  10. })
  11. // 这里有一些代码
  12. // 在这里,我想向上下文日志记录器cl添加一个额外的字段。我该如何做到这一点?
  13. }

编辑

正如ymonad提到的,可以通过覆盖contextLogger来实现。还发现可以添加一个额外的字段:

  1. 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.

  1. package main
  2. import (
  3. "github.com/Sirupsen/logrus"
  4. )
  5. func main() {
  6. logrus.Info("normal logger")
  7. cl := logrus.WithFields(
  8. logrus.Fields{
  9. "extra_field_one": "extra_value_one",
  10. })
  11. // some code here
  12. // here I want to add an additional field to to contextlogger cl.
  13. // How do I do that?
  14. }

EDIT

As ymonad mentioned, it's possible by overwriting the contextLogger. Also found out that you can add one additional field:

  1. cl = cl.WithField("key", "value")

答案1

得分: 18

你可以直接调用cl.WithFields()函数。

  1. package main
  2. import "github.com/Sirupsen/logrus"
  3. func main() {
  4. cl := logrus.WithFields(
  5. logrus.Fields{
  6. "extra_field_one": "extra_value_one",
  7. })
  8. cl = cl.WithFields(
  9. logrus.Fields{
  10. "extra_field_two": "extra_value_two",
  11. })
  12. cl.Info("hello world")
  13. }

输出结果为:

  1. INFO[0000] hello world extra_field_one="extra_value_one" extra_field_two="extra_value_two"
英文:

You can just call cl.WithFields()

  1. package main
  2. import "github.com/Sirupsen/logrus"
  3. func main() {
  4. cl := logrus.WithFields(
  5. logrus.Fields{
  6. "extra_field_one": "extra_value_one",
  7. })
  8. cl = cl.WithFields(
  9. logrus.Fields{
  10. "extra_field_two": "extra_value_two",
  11. })
  12. cl.Info("hello world")
  13. }

Output is:

  1. 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:

确定