]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blame - api/logger.go
Augment log messages.
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / api / logger.go
CommitLineData
7a9e5112 1package api
2
3import (
372ed740 4 "fmt"
5 "strings"
6 "time"
7
8 "github.com/Sirupsen/logrus"
7a9e5112 9 "github.com/gin-gonic/gin"
10 "github.com/jloup/utils"
11)
12
13var log = utils.StandardL().WithField("module", "api")
14
15func Logger() gin.HandlerFunc {
16 return func(c *gin.Context) {
17 path := c.Request.URL.Path
372ed740 18 start := time.Now()
7a9e5112 19 rawQuery := c.Request.URL.RawQuery
20
21 c.Next()
22
372ed740 23 latency := time.Now().Sub(start).Round(10 * time.Microsecond)
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)
7a9e5112 41
372ed740 42 msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path)
7a9e5112 43
372ed740 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
7a9e5112 52 }
372ed740 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)
7a9e5112 60 }
61}