Skip to content

Commit

Permalink
fix: Add request meta data when logging request error.
Browse files Browse the repository at this point in the history
fix #41

co-author: @emidander
  • Loading branch information
appleboy committed Sep 14, 2022
1 parent 3542732 commit 30de6b1
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,28 @@ func GinzapWithConfig(logger *zap.Logger, conf *Config) gin.HandlerFunc {
end = end.UTC()
}

fields := []zapcore.Field{
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.Duration("latency", latency),
}
if conf.TimeFormat != "" {
fields = append(fields, zap.String("time", end.Format(conf.TimeFormat)))
}
if conf.TraceID {
fields = append(fields, zap.String("traceID", trace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()))
}

if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
for _, e := range c.Errors.Errors() {
logger.Error(e)
logger.Error(e, fields...)
}
} else {
fields := []zapcore.Field{
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.Duration("latency", latency),
}
if conf.TimeFormat != "" {
fields = append(fields, zap.String("time", end.Format(conf.TimeFormat)))
}
if conf.TraceID {
fields = append(fields, zap.String("traceID", trace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()))
}
logger.Info(path, fields...)
}
}
Expand Down

0 comments on commit 30de6b1

Please sign in to comment.