diff options
Diffstat (limited to 'api')
-rw-r--r-- | api/logger.go | 46 |
1 files changed, 40 insertions, 6 deletions
diff --git a/api/logger.go b/api/logger.go index 7057a30..a24e08a 100644 --- a/api/logger.go +++ b/api/logger.go | |||
@@ -1,6 +1,11 @@ | |||
1 | package api | 1 | package api |
2 | 2 | ||
3 | import ( | 3 | import ( |
4 | "fmt" | ||
5 | "strings" | ||
6 | "time" | ||
7 | |||
8 | "github.com/Sirupsen/logrus" | ||
4 | "github.com/gin-gonic/gin" | 9 | "github.com/gin-gonic/gin" |
5 | "github.com/jloup/utils" | 10 | "github.com/jloup/utils" |
6 | ) | 11 | ) |
@@ -10,18 +15,47 @@ var log = utils.StandardL().WithField("module", "api") | |||
10 | func Logger() gin.HandlerFunc { | 15 | func Logger() gin.HandlerFunc { |
11 | return func(c *gin.Context) { | 16 | return func(c *gin.Context) { |
12 | path := c.Request.URL.Path | 17 | path := c.Request.URL.Path |
18 | start := time.Now() | ||
13 | rawQuery := c.Request.URL.RawQuery | 19 | rawQuery := c.Request.URL.RawQuery |
14 | 20 | ||
15 | c.Next() | 21 | c.Next() |
16 | 22 | ||
17 | for _, err := range c.Errors { | 23 | latency := time.Now().Sub(start).Round(10 * time.Microsecond) |
18 | l := log.WithField("path", path) | 24 | code := c.Writer.Status() |
25 | |||
26 | l := log | ||
27 | l = l.WithField("latency", latency) | ||
28 | l = l.WithField("client_ip", c.ClientIP()) | ||
29 | l = l.WithField("method", c.Request.Method) | ||
30 | l = l.WithField("status_code", code) | ||
31 | |||
32 | if _, exists := c.Get("user"); exists { | ||
33 | l = l.WithField("user_id", GetUser(c).Id) | ||
34 | } | ||
35 | |||
36 | if rawQuery != "" { | ||
37 | path = fmt.Sprintf("%s?%s", path, rawQuery) | ||
38 | } | ||
39 | |||
40 | l = l.WithField("path", path) | ||
19 | 41 | ||
20 | if rawQuery != "" { | 42 | msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path) |
21 | l = l.WithField("query", rawQuery) | ||
22 | } | ||
23 | 43 | ||
24 | l.Errorf("%s", err.Err) | 44 | var level logrus.Level |
45 | switch { | ||
46 | case code >= 200 && code < 400: | ||
47 | level = logrus.InfoLevel | ||
48 | case code >= 400 && code < 500: | ||
49 | level = logrus.WarnLevel | ||
50 | default: | ||
51 | level = logrus.ErrorLevel | ||
25 | } | 52 | } |
53 | |||
54 | comment := c.Errors.ByType(gin.ErrorTypePrivate).String() | ||
55 | if comment != "" { | ||
56 | msgLog = fmt.Sprintf("%s: %s", msgLog, strings.TrimSpace(comment)) | ||
57 | } | ||
58 | |||
59 | l.Logf(level, msgLog) | ||
26 | } | 60 | } |
27 | } | 61 | } |