|
| 1 | +// Package ginzap provides log handling using zap package. |
| 2 | +// Code structure based on ginrus package. |
| 3 | +package log |
| 4 | + |
| 5 | +import ( |
| 6 | + "net" |
| 7 | + "net/http" |
| 8 | + "net/http/httputil" |
| 9 | + "os" |
| 10 | + "runtime/debug" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/gin-gonic/gin" |
| 15 | + "go.uber.org/zap" |
| 16 | +) |
| 17 | + |
| 18 | +// Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap. |
| 19 | +// |
| 20 | +// Requests with errors are logged using zap.Error(). |
| 21 | +// Requests without errors are logged using zap.Info(). |
| 22 | +// |
| 23 | +// It receives: |
| 24 | +// 1. A time package format string (e.g. time.RFC3339). |
| 25 | +// 2. A boolean stating whether to use UTC time zone or local. |
| 26 | +func Ginzap(logger *zap.Logger, timeFormat string, utc bool) gin.HandlerFunc { |
| 27 | + return func(c *gin.Context) { |
| 28 | + start := time.Now() |
| 29 | + // some evil middlewares modify this values |
| 30 | + path := c.Request.URL.Path |
| 31 | + query := c.Request.URL.RawQuery |
| 32 | + c.Next() |
| 33 | + |
| 34 | + end := time.Now() |
| 35 | + latency := end.Sub(start) |
| 36 | + if utc { |
| 37 | + end = end.UTC() |
| 38 | + } |
| 39 | + |
| 40 | + if len(c.Errors) > 0 { |
| 41 | + // Append error field if this is an erroneous request. |
| 42 | + for _, e := range c.Errors.Errors() { |
| 43 | + logger.Error(e) |
| 44 | + } |
| 45 | + } |
| 46 | + logger.Info(path, |
| 47 | + zap.Int("status", c.Writer.Status()), |
| 48 | + zap.String("method", c.Request.Method), |
| 49 | + zap.String("path", path), |
| 50 | + zap.String("query", query), |
| 51 | + zap.String("ip", c.ClientIP()), |
| 52 | + zap.String("user-agent", c.Request.UserAgent()), |
| 53 | + zap.String("time", end.Format(timeFormat)), |
| 54 | + zap.Duration("latency", latency), |
| 55 | + ) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// RecoveryWithZap returns a gin.HandlerFunc (middleware) |
| 60 | +// that recovers from any panics and logs requests using uber-go/zap. |
| 61 | +// All errors are logged using zap.Error(). |
| 62 | +// stack means whether output the stack info. |
| 63 | +// The stack info is easy to find where the error occurs but the stack info is too large. |
| 64 | +func RecoveryWithZap(logger *zap.Logger, stack bool) gin.HandlerFunc { |
| 65 | + return func(c *gin.Context) { |
| 66 | + defer func() { |
| 67 | + if err := recover(); err != nil { |
| 68 | + // Check for a broken connection, as it is not really a |
| 69 | + // condition that warrants a panic stack trace. |
| 70 | + var brokenPipe bool |
| 71 | + if ne, ok := err.(*net.OpError); ok { |
| 72 | + if se, ok := ne.Err.(*os.SyscallError); ok { |
| 73 | + if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { |
| 74 | + brokenPipe = true |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + httpRequest, _ := httputil.DumpRequest(c.Request, false) |
| 80 | + if brokenPipe { |
| 81 | + logger.Error(c.Request.URL.Path, |
| 82 | + zap.Any("error", err), |
| 83 | + zap.String("request", string(httpRequest)), |
| 84 | + ) |
| 85 | + // If the connection is dead, we can't write a status to it. |
| 86 | + c.Error(err.(error)) // nolint: errcheck |
| 87 | + c.Abort() |
| 88 | + return |
| 89 | + } |
| 90 | + |
| 91 | + if stack { |
| 92 | + logger.Error("[Recovery from panic]", |
| 93 | + zap.Time("time", time.Now()), |
| 94 | + zap.Any("error", err), |
| 95 | + zap.String("request", string(httpRequest)), |
| 96 | + zap.String("stack", string(debug.Stack())), |
| 97 | + ) |
| 98 | + } else { |
| 99 | + logger.Error("[Recovery from panic]", |
| 100 | + zap.Time("time", time.Now()), |
| 101 | + zap.Any("error", err), |
| 102 | + zap.String("request", string(httpRequest)), |
| 103 | + ) |
| 104 | + } |
| 105 | + c.AbortWithStatus(http.StatusInternalServerError) |
| 106 | + } |
| 107 | + }() |
| 108 | + c.Next() |
| 109 | + } |
| 110 | +} |
0 commit comments