英文:
Zap logger values
问题
你好,我想使用zap全局记录器。
目前我是这样使用的:
zap.L().Error("error receive",
zap.Error(err),
zap.String("uuid", msg.Id.String()),
zap.String("msg_f", string(msg_f)),
)
但唯一的问题是,由于uuid和msg的类型问题,我遇到了错误。
type Message struct {
Id uuid.UUID
}
而msg_f的类型是[]byte,请问我应该如何打印它们,但我不知道应该使用什么方法。
英文:
Hello I want to use zap global logger
right now I am using like this
zap.L().Error("error receive",
zap.Error(err),
zap.String("uuid", msg.Id)
zap.String("msg_f", msg_f),
)
but the only problem is I am getting errors because of types of uuid and msg
type Message struct {
Id uuid.UUID
}
and msg_f type is []byte my question how can I print them but I don't what should I use
答案1
得分: 3
zap.String 的定义如下:
func String(key string, val string) Field
所以第二个参数是一个 string;UUID/[]byte 不是一个 string,所以不能直接使用。这给你留下了两个选择:
- 将你拥有的内容转换为
string,然后将其传递给zap.String; - 使用接受你想要记录的类型的函数。
zap 提供了一些返回 Field 的函数,其中一些接受 []byte(例如 Binary 和 ByteString)。zap 还提供了 Stringer,你可以将其与任何实现了 fmt.Stringer 接口的类型一起使用(UUID 就实现了该接口)。
下面的示例(playground)演示了这一点:
zap.L().Error("error receive",
zap.Error(err),
zap.String("uuid", msg.Id.String()),
zap.Stringer("uuid2", msg.Id),
zap.ByteString("msg_f", msg_f),
zap.Binary("msg_f2", msg_f),
zap.String("msg_f3", string(msg_f)),
)
英文:
The definition of zap.String is:
func String(key string, val string) Field
So the second argument is a string; a UUID/[]byte is not a string so cannot be used as-is. This leaves you with two options:
- Pass a
stringtozap.String(converting what you have into astring) or; - Use a function that accepts the type you want to log.
zap provides a number of functions that return a Field some of which accept []byte (e.g. Binary and ByteString. zap also provides Stringer which you can use with any type that implements the fmt.Stringer interface (which UUID does).
The below (playground) demonstrates:
zap.L().Error("error receive",
zap.Error(err),
zap.String("uuid", msg.Id.String()),
zap.Stringer("uuid2", msg.Id),
zap.ByteString("msg_f", msg_f),
zap.Binary("msg_f2", msg_f),
zap.String("msg_f3", string(msg_f)),
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论