Search code examples
gogo-zap

Zap logger values


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


Solution

  • 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 string to zap.String (converting what you have into a string) 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)),
        )