-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin_gcplog.go
64 lines (50 loc) · 1.17 KB
/
gin_gcplog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package gcplog
import (
"bytes"
"fmt"
"time"
"github.com/gin-gonic/gin"
)
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func Gin(gcplog *GcpLog) gin.HandlerFunc {
return func(c *gin.Context) {
// before request
// log the body maybe..
// ...do something
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = blw
defer func(begin time.Time) {
// after request
status := c.Writer.Status()
log := c.Request.Method + " " + c.Request.URL.Path
responseMeta := ResponseMetadata{
Status: c.Writer.Status(),
Size: c.Writer.Size(),
Latency: time.Since(begin),
}
if status < 400 {
gcplog.LogRM(log, c.Request, &responseMeta)
return
}
var err error
if len(c.Errors) > 0 {
err = c.Errors.Last().Err
} else {
err = fmt.Errorf(blw.body.String())
}
if status >= 400 && status < 500 {
gcplog.WarnRM(err, c.Request, &responseMeta)
} else {
gcplog.ErrorRM(err, c.Request, &responseMeta)
}
}(time.Now())
c.Next()
}
}