From 30de6b1fdab89dfb3e7308e00ef5382fb47e3486 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Wed, 14 Sep 2022 09:24:06 +0800 Subject: [PATCH] fix: Add request meta data when logging request error. fix https://github.com/gin-contrib/zap/pull/41 co-author: @emidander --- zap.go | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/zap.go b/zap.go index 0c2cc6d..3ed42b5 100644 --- a/zap.go +++ b/zap.go @@ -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...) } }