]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blob - api/logger.go
Context log fields.
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / api / logger.go
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 SetContextLogField(c *gin.Context, field string, value interface{}) {
15 itf, ok := c.Get("logFields")
16 var fields map[string]interface{}
17 if !ok {
18 fields = make(map[string]interface{})
19 } else {
20 fields = itf.(map[string]interface{})
21 }
22
23 fields[field] = value
24 c.Set("logFields", fields)
25 }
26
27 func Logger() gin.HandlerFunc {
28 return func(c *gin.Context) {
29 path := c.Request.URL.Path
30 rawQuery := c.Request.URL.RawQuery
31 start := time.Now()
32
33 c.Next()
34
35 latency := time.Now().Sub(start).Round(10 * time.Microsecond)
36 code := c.Writer.Status()
37
38 l := log
39 l = l.WithField("latency", latency)
40 l = l.WithField("client_ip", c.ClientIP())
41 l = l.WithField("method", c.Request.Method)
42 l = l.WithField("status_code", code)
43
44 if itf, ok := c.Get("logFields"); ok {
45 for field, value := range itf.(map[string]interface{}) {
46 l = l.WithField(field, value)
47 }
48 }
49
50 if rawQuery != "" {
51 path = fmt.Sprintf("%s?%s", path, rawQuery)
52 }
53
54 l = l.WithField("path", path)
55
56 msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path)
57
58 var level logrus.Level
59 switch {
60 case code >= 200 && code < 400:
61 level = logrus.DebugLevel
62 case code >= 400 && code < 500:
63 level = logrus.InfoLevel
64 default:
65 level = logrus.ErrorLevel
66 }
67
68 errors := c.Errors.ByType(gin.ErrorTypePrivate)
69
70 for _, err := range errors {
71 l.WithField("description", err.Err).Logf(level, "%s: %s", msgLog, err.Err)
72 }
73
74 if errors == nil {
75 l.Logf(level, msgLog)
76 }
77 }
78 }