第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何復(fù)制輸入鍵并將其顯示在與 Uber Zap 相同的日志中?

如何復(fù)制輸入鍵并將其顯示在與 Uber Zap 相同的日志中?

Go
慕碼人2483693 2022-10-24 16:32:27
我想caller用另一個鍵名復(fù)制輸入鍵method并在日志中顯示...{"level":"error", "caller: "testing/testing.go:1193", "method": "testing/testing.go:1193", "message": "foo"}有任何想法嗎?
查看完整描述

1 回答

?
哆啦的時光機(jī)

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個贊

您不能更改 a 的字段zapcore.Entry。你可以改變它的編組方式,但老實(shí)說,將幽靈字段添加到結(jié)構(gòu)中是一個糟糕的 hack。您可以做的是使用自定義編碼器,并將[]zapcore.Field調(diào)用者的副本附加到新的字符串項(xiàng)。特別是,JSON 編碼器的默認(rèn)輸出來自Caller.TrimmedPath():


type duplicateCallerEncoder struct {

    zapcore.Encoder

}


func (e *duplicateCallerEncoder) Clone() zapcore.Encoder {

    return &duplicateCallerEncoder{Encoder: e.Encoder.Clone()}

}


func (e *duplicateCallerEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {

    // appending to the fields list

    fields = append(fields, zap.String("method", entry.Caller.TrimmedPath()))

    return e.Encoder.EncodeEntry(entry, fields)

}

請注意,上述實(shí)現(xiàn)Encoder.Clone(). 有關(guān)詳細(xì)信息,請參閱:為什么在 Uber Zap 中調(diào)用 logger.With 后自定義編碼丟失?


然后您可以通過構(gòu)建新的 Zap 核心或注冊自定義編碼器來使用它。注冊的構(gòu)造函數(shù)將 a 嵌入JSONEncoder到您的自定義編碼器中,這是生產(chǎn)記錄器的默認(rèn)編碼器:


func init() {

    // name is whatever you like

    err := zap.RegisterEncoder("duplicate-caller", func(config zapcore.EncoderConfig) (zapcore.Encoder, error) {

        return &duplicateCallerEncoder{Encoder: zapcore.NewJSONEncoder(config)}, nil

    })

    // it's reasonable to panic here, since the program can't initialize

    if err != nil {

        panic(err)

    }

}


func main() {

    cfg := zap.NewProductionConfig()

    cfg.Encoding = "duplicate-caller"

    logger, _ := cfg.Build()

    logger.Info("this is info")

}

以上使用您的自定義配置復(fù)制了生產(chǎn)記錄器的初始化。


對于這樣一個簡單的配置,我更喜歡init()使用zap.RegisterEncoder. 如果需要,和/或如果您將其放在其他包中,它可以更快地重構(gòu)代碼。您當(dāng)然可以在main(); 或者如果您需要額外的定制,那么您可以使用zap.New(zapcore.NewCore(myCustomEncoder, /* other args */))


你可以在這個操場上看到完整的程序:https ://go.dev/play/p/YLDXbdZ-qZP


它輸出:


{"level":"info","ts":1257894000,"caller":"sandbox3965111040/prog.go:24","msg":"this is info","method":"sandbox3965111040/prog.go:24"}



查看完整回答
反對 回復(fù) 2022-10-24
  • 1 回答
  • 0 關(guān)注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號