我想caller用另一個鍵名復制輸入鍵method并在日志中顯示...
{"level":"error", "caller: "testing/testing.go:1193", "method": "testing/testing.go:1193", "message": "foo"}
有任何想法嗎?
uj5u.com熱心網友回復:
您不能更改 a 的欄位zapcore.Entry。你可以改變它的編組方式,但老實說,將幽靈欄位添加到結構中是一個糟糕的 hack。您可以做的是使用自定義編碼器,并將[]zapcore.Field呼叫者的副本附加到新的字串項。特別是,JSON 編碼器的默認輸出來自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)
}
請注意,上述實作Encoder.Clone(). 有關詳細資訊,請參閱:為什么在 Uber Zap 中呼叫 logger.With 后自定義編碼丟失?
然后您可以通過構建新的 Zap 核心或注冊自定義編碼器來使用它。注冊的建構式將 a 嵌入JSONEncoder到您的自定義編碼器中,這是生產記錄器的默認編碼器:
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")
}
以上使用您的自定義配置復制了生產記錄器的初始化。
對于這樣一個簡單的配置,我更喜歡init()使用zap.RegisterEncoder. 如果需要,和/或如果您將其放在其他包中,它可以更快地重構代碼。您當然可以在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"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414943.html
標籤:
