]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/commitdiff
Context log fields. v0.0.19
authorjloup <jloup@jloup.work>
Wed, 16 May 2018 22:09:08 +0000 (00:09 +0200)
committerjloup <jloup@jloup.work>
Wed, 16 May 2018 22:09:08 +0000 (00:09 +0200)
api/auth_jwt.go
api/logger.go

index 88ccda84bd161e133b9c59ff3cf0c1f094510f76..27cc3b0797d8f272cbcc35c968d52e45ea30c49a 100644 (file)
@@ -92,6 +92,7 @@ func JwtAuth(c *gin.Context) *Error {
 
        c.Set("user", *user)
        c.Set("claims", claims)
+       SetContextLogField(c, "user_id", user.Id)
 
        return nil
 }
index 1016863dd8318609f8c0dd8026f878bb85c12919..ea7266ba4fe450e4bb406afe7dee7adb693d2b86 100644 (file)
@@ -11,11 +11,24 @@ import (
 
 var log = utils.StandardL().WithField("module", "api")
 
+func SetContextLogField(c *gin.Context, field string, value interface{}) {
+       itf, ok := c.Get("logFields")
+       var fields map[string]interface{}
+       if !ok {
+               fields = make(map[string]interface{})
+       } else {
+               fields = itf.(map[string]interface{})
+       }
+
+       fields[field] = value
+       c.Set("logFields", fields)
+}
+
 func Logger() gin.HandlerFunc {
        return func(c *gin.Context) {
                path := c.Request.URL.Path
-               start := time.Now()
                rawQuery := c.Request.URL.RawQuery
+               start := time.Now()
 
                c.Next()
 
@@ -28,8 +41,10 @@ func Logger() gin.HandlerFunc {
                l = l.WithField("method", c.Request.Method)
                l = l.WithField("status_code", code)
 
-               if _, exists := c.Get("user"); exists {
-                       l = l.WithField("user_id", GetUser(c).Id)
+               if itf, ok := c.Get("logFields"); ok {
+                       for field, value := range itf.(map[string]interface{}) {
+                               l = l.WithField(field, value)
+                       }
                }
 
                if rawQuery != "" {