Hello I am trying to change sugar logger to global longer I checked possible fields which I can use but I couldn't something solve my problem
for example in some situations I use
zap.L().Debug("recv_cmd",
zap.String("user", c.GetString("user")),
zap.String("path", c.Request.URL.Path),
)
This is what I use in most of the cases but I have one different case which like this
params := make([]interface{}, 0, 20)
params = append(params,
"status", c.Writer.Status(),
"method", c.Request.Method
"path", c.Request.URL.Path,
"ip", c.ClientIP(),
)
if len(body) > 0 {
params = append(params, "body", string(body))
}
so in this case, I don't have a body in every request, so params obj doesn't have the same struck for each request
what I want is (this is just a simple demonstration I know stringer won't work)
zap.L().Info("Info",
zap.Stringer("request", params...),
)
The definition of Logger.Info is:
func (log *Logger) Info(msg string, fields ...Field)
and the definition of zap.Stringer is:
func Stringer(key string, val fmt.Stringer) Field
So there are a number of issues with what you are attempting:
[]interface{}
to a function that accepts fmt.Stringer
(because it does not implement the interface).zap.Stringer
returns a single Field
whereas you are really trying to log multiple fields.What I think you are trying to accomplish is (playground) (but I'm not really clear whether params
is being created specifically for logging or for another reason):
var params []zap.Field
params = append(params,
zap.String("status", c.Status),
zap.String("method", c.Method),
zap.String("path", c.URL.Path),
zap.String("ip", c.ClientIP),
)
if len(body) > 0 {
params = append(params, zap.String("body", string(body)))
}
zap.L().Info("Info", params...)
If that does not do what you are doing take a look at the variety of encoders that zap provides (e.g. Any
, Inline
etc).
Note: I have simplified your structure somewhat (because you did not include details). It is easier to answer questions like this if you include a minimum reproducible example (i.e. you should define structures used but only to the degree needed to illustrate the issue).