-
Notifications
You must be signed in to change notification settings - Fork 219
/
logging.go
89 lines (72 loc) 路 2.04 KB
/
logging.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package middleware
import (
"bytes"
"encoding/json"
"io/ioutil"
"regexp"
"time"
"github.com/gin-gonic/gin"
"github.com/willf/pad"
"github.com/1024casts/snake/handler"
"github.com/1024casts/snake/pkg/errno"
"github.com/1024casts/snake/pkg/log"
)
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)
}
// Logging is a middleware function that logs the each request.
func Logging() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now().UTC()
path := c.Request.URL.Path
reg := regexp.MustCompile("(/v1/user|/login)")
if !reg.MatchString(path) {
return
}
// Skip for the health check requests.
if path == "/sd/health" || path == "/sd/ram" || path == "/sd/cpu" || path == "/sd/disk" {
return
}
// Read the Body content
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}
// Restore the io.ReadCloser to its original state
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// The basic informations.
method := c.Request.Method
ip := c.ClientIP()
//log.Debugf("New request come in, path: %s, Method: %s, body `%s`", path, method, string(bodyBytes))
blw := &bodyLogWriter{
body: bytes.NewBufferString(""),
ResponseWriter: c.Writer,
}
c.Writer = blw
// Continue.
c.Next()
// Calculates the latency.
end := time.Now().UTC()
latency := end.Sub(start)
var code int
var message string
// get code and message
var response handler.Response
if err := json.Unmarshal(blw.body.Bytes(), &response); err != nil {
log.Errorf("response body can not unmarshal to model.Response struct, body: `%s`, err: %+v",
blw.body.Bytes(), err)
code = errno.InternalServerError.Code
message = err.Error()
} else {
code = response.Code
message = response.Message
}
log.Infof("%-13s | %-12s | %s %s | {code: %d, message: %s}", latency, ip,
pad.Right(method, 5, ""), path, code, message)
}
}