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