github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/gin_app/logger.go (about) 1 package gin_app 2 3 import ( 4 "os" 5 6 "github.com/gin-gonic/gin" 7 "github.com/google/uuid" 8 "github.com/sirupsen/logrus" 9 10 "github.com/johnnyeven/libtools/courier/status_error" 11 "github.com/johnnyeven/libtools/duration" 12 "github.com/johnnyeven/libtools/log/context" 13 ) 14 15 var ( 16 REQUEST_ID_NAME = "x-request-id" 17 ProjectRef = os.Getenv("PROJECT_REF") 18 ) 19 20 func Logger() gin.HandlerFunc { 21 return func(c *gin.Context) { 22 d := duration.NewDuration() 23 24 reqID := c.Request.Header.Get(REQUEST_ID_NAME) 25 26 if reqID == "" { 27 reqID = uuid.New().String() 28 } 29 30 c.Set(REQUEST_ID_NAME, reqID) 31 c.Header("X-Reversion", ProjectRef) 32 33 context.SetLogID(reqID) 34 35 fields := logrus.Fields{ 36 "tag": "access", 37 "log_id": reqID, 38 "remote_ip": c.ClientIP(), 39 "method": c.Request.Method, 40 "pathname": c.Request.URL.Path, 41 } 42 43 c.Next() 44 45 fields["status"] = c.Writer.Status() 46 fields["request_time"] = d.Get() 47 48 logger := logrus.WithFields(fields) 49 50 if len(c.Errors) > 0 { 51 for _, err := range c.Errors { 52 statusErr := status_error.FromError(err.Err) 53 if statusErr.Status() >= 500 { 54 logger.Errorf(statusErr.Error()) 55 } else { 56 logger.Warnf(statusErr.Error()) 57 } 58 } 59 } else { 60 logger.Info("") 61 } 62 } 63 }