Skip to content

Commit f5d9692

Browse files
committed
deps(api): Vendor ginzap into middleware
Vendor ginzap to log responses in case of error
1 parent 46c4dec commit f5d9692

4 files changed

Lines changed: 113 additions & 4 deletions

File tree

‎api/go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ go 1.16
44

55
require (
66
github.com/coreos/go-oidc v2.2.1+incompatible
7+
github.com/dgrijalva/jwt-go v3.2.0+incompatible
78
github.com/fsnotify/fsnotify v1.4.9 // indirect
89
github.com/gin-contrib/sessions v0.0.3
9-
github.com/gin-contrib/zap v0.0.1
1010
github.com/gin-gonic/gin v1.7.1
1111
github.com/go-playground/validator/v10 v10.6.1 // indirect
1212
github.com/golang/protobuf v1.5.2 // indirect

‎api/go.sum‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7Do
9595
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
9696
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
9797
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
98+
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
9899
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
99100
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
100101
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
@@ -118,8 +119,6 @@ github.com/gin-contrib/sessions v0.0.3 h1:PoBXki+44XdJdlgDqDrY5nDVe3Wk7wDV/UCOuL
118119
github.com/gin-contrib/sessions v0.0.3/go.mod h1:8C/J6cad3Il1mWYYgtw0w+hqasmpvy25mPkXdOgeB9I=
119120
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
120121
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
121-
github.com/gin-contrib/zap v0.0.1 h1:wsX/ahRftxPiXpiUw0YqyHj+TQTKtv+DAFWH84G1Uvg=
122-
github.com/gin-contrib/zap v0.0.1/go.mod h1:vJJndZ8f44gsTHQrDPIB4YOZzwOwiEIdE0mMrZLOogk=
123122
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
124123
github.com/gin-gonic/gin v1.7.1 h1:qC89GU3p8TvKWMAVhEpmpB2CIb1hnqt2UdKZaP93mS8=
125124
github.com/gin-gonic/gin v1.7.1/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=

‎api/middleware/log/ginzap.go‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
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+
}

‎api/routers/routers.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ import (
44
"net/http"
55
"time"
66

7-
ginzap "github.com/gin-contrib/zap"
87
"github.com/gin-gonic/gin"
98
"go.uber.org/zap"
109

1110
"agones-minecraft/config"
1211
v1Controllers "agones-minecraft/controllers/api/v1"
1312
"agones-minecraft/middleware/errors"
13+
ginzap "agones-minecraft/middleware/log"
1414
"agones-minecraft/middleware/session"
1515
)
1616

0 commit comments

Comments
 (0)