1 回答

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"}
- 1 回答
- 0 關(guān)注
- 96 瀏覽
添加回答
舉報(bào)