-
Notifications
You must be signed in to change notification settings - Fork 21
/
util.go
50 lines (45 loc) · 1.14 KB
/
util.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
package main
import (
"fmt"
"math"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// Logger is the logrus logger handler
func ginLogger(logger logrus.FieldLogger) gin.HandlerFunc {
return func(c *gin.Context) {
// other handler can change c.Path so:
path := c.Request.URL.Path
start := time.Now()
c.Next()
stop := time.Since(start)
latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
statusCode := c.Writer.Status()
dataLength := c.Writer.Size()
if dataLength < 0 {
dataLength = 0
}
entry := logger.WithFields(logrus.Fields{
"statusCode": statusCode,
"latency": latency, // time to process
"method": c.Request.Method,
"path": path,
"dataLength": dataLength,
})
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
} else {
msg := fmt.Sprintf("%s %s %d (%dms)", c.Request.Method, path, statusCode, latency)
//nolint:gocritic
if statusCode >= http.StatusInternalServerError {
entry.Error(msg)
} else if statusCode >= http.StatusBadRequest {
entry.Warn(msg)
} else {
entry.Debug(msg)
}
}
}
}