]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blame - api/logger.go
Context log fields.
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / api / logger.go
CommitLineData
7a9e5112 1package api
2
3import (
372ed740 4 "fmt"
372ed740 5 "time"
6
7 "github.com/Sirupsen/logrus"
7a9e5112 8 "github.com/gin-gonic/gin"
9 "github.com/jloup/utils"
10)
11
12var log = utils.StandardL().WithField("module", "api")
13
e0ab9e8c 14func 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
7a9e5112 27func Logger() gin.HandlerFunc {
28 return func(c *gin.Context) {
29 path := c.Request.URL.Path
30 rawQuery := c.Request.URL.RawQuery
e0ab9e8c 31 start := time.Now()
7a9e5112 32
33 c.Next()
34
372ed740 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
e0ab9e8c 44 if itf, ok := c.Get("logFields"); ok {
45 for field, value := range itf.(map[string]interface{}) {
46 l = l.WithField(field, value)
47 }
372ed740 48 }
49
50 if rawQuery != "" {
51 path = fmt.Sprintf("%s?%s", path, rawQuery)
52 }
53
54 l = l.WithField("path", path)
7a9e5112 55
372ed740 56 msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path)
7a9e5112 57
372ed740 58 var level logrus.Level
59 switch {
60 case code >= 200 && code < 400:
4059b21b 61 level = logrus.DebugLevel
372ed740 62 case code >= 400 && code < 500:
4059b21b 63 level = logrus.InfoLevel
372ed740 64 default:
65 level = logrus.ErrorLevel
7a9e5112 66 }
372ed740 67
ecb0fb69 68 errors := c.Errors.ByType(gin.ErrorTypePrivate)
4495b984 69
70 for _, err := range errors {
4059b21b 71 l.WithField("description", err.Err).Logf(level, "%s: %s", msgLog, err.Err)
372ed740 72 }
73
4495b984 74 if errors == nil {
75 l.Logf(level, msgLog)
76 }
7a9e5112 77 }
78}