dqmdlo9674 2017-03-21 07:23 采纳率: 100%
浏览 358
已采纳

Logrus向contextlogger添加额外的字段

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条回答 默认 最新

  • duanlvji4780 2017-03-21 08:12
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测