]>
Commit | Line | Data |
---|---|---|
1 | package api | |
2 | ||
3 | import ( | |
4 | "fmt" | |
5 | "time" | |
6 | ||
7 | "github.com/Sirupsen/logrus" | |
8 | "github.com/gin-gonic/gin" | |
9 | "github.com/jloup/utils" | |
10 | ) | |
11 | ||
12 | var log = utils.StandardL().WithField("module", "api") | |
13 | ||
14 | func Logger() gin.HandlerFunc { | |
15 | return func(c *gin.Context) { | |
16 | path := c.Request.URL.Path | |
17 | start := time.Now() | |
18 | rawQuery := c.Request.URL.RawQuery | |
19 | ||
20 | c.Next() | |
21 | ||
22 | latency := time.Now().Sub(start).Round(10 * time.Microsecond) | |
23 | code := c.Writer.Status() | |
24 | ||
25 | l := log | |
26 | l = l.WithField("latency", latency) | |
27 | l = l.WithField("client_ip", c.ClientIP()) | |
28 | l = l.WithField("method", c.Request.Method) | |
29 | l = l.WithField("status_code", code) | |
30 | ||
31 | if _, exists := c.Get("user"); exists { | |
32 | l = l.WithField("user_id", GetUser(c).Id) | |
33 | } | |
34 | ||
35 | if rawQuery != "" { | |
36 | path = fmt.Sprintf("%s?%s", path, rawQuery) | |
37 | } | |
38 | ||
39 | l = l.WithField("path", path) | |
40 | ||
41 | msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path) | |
42 | ||
43 | var level logrus.Level | |
44 | switch { | |
45 | case code >= 200 && code < 400: | |
46 | level = logrus.InfoLevel | |
47 | case code >= 400 && code < 500: | |
48 | level = logrus.WarnLevel | |
49 | default: | |
50 | level = logrus.ErrorLevel | |
51 | } | |
52 | ||
53 | errors := c.Errors | |
54 | log.Infof("TMP %s '%v'", msgLog, errors) | |
55 | ||
56 | for _, err := range errors { | |
57 | l.Logf(level, "%s: %s", msgLog, err.Err) | |
58 | } | |
59 | ||
60 | if errors == nil { | |
61 | l.Logf(level, msgLog) | |
62 | } | |
63 | } | |
64 | } |