package ginutils import ( "time" "git.dev.m-and-m.ovh/mderasse/gocommon/webserver" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) // Log will create a new logrus entry and add it to the context. // That logrus entry will include some useful extra fields. func Log(l *logrus.Entry) gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() // construct default fields fields := logrus.Fields{ string(LogField_IP): webserver.GetClientIP(c.Request), // Request information string(LogField_Method): c.Request.Method, string(LogField_CanonPath): c.FullPath(), string(LogField_Path): c.Request.URL.String(), string(LogField_RequestID): c.GetString(string(ContextKey_RequestID)), } // create the logrus entry and add it to gin context log := l.Logger.WithFields(fields) c.Set(string(ContextKey_Logger), log) log.Info("[start]") c.Next() log.WithFields( logrus.Fields{ string(LogField_Duration): time.Since(start).Microseconds(), string(LogField_StatusCode): c.Writer.Status(), }).Info("[end]") } } // GetLogger will retrieve a logger instance from gin context and return it or return false. func GetLogger(c *gin.Context) (*logrus.Entry, bool) { if log, exist := c.Get(string(ContextKey_Logger)); exist { return log.(*logrus.Entry), true } return nil, false } // GetLoggerWithField will add a key and value field to the logger, update the gin context, and return the new logger. func GetLoggerWithField(c *gin.Context, key string, value interface{}) *logrus.Entry { iLog, exist := c.Get(string(ContextKey_Logger)) if !exist { panic("no logger in context") } log, ok := iLog.(*logrus.Entry) if !ok { panic("invalid logger in context") } log = log.WithField(key, value) c.Set(string(ContextKey_Logger), log) return log } // GetLoggerWithFields will add provided fields to the logger, update the gin context, and return the new logger. func GetLoggerWithFields(c *gin.Context, fields logrus.Fields) *logrus.Entry { iLog, exist := c.Get(string(ContextKey_Logger)) if !exist { panic("no logger in context") } log, ok := iLog.(*logrus.Entry) if !ok { panic("invalid logger in context") } log = log.WithFields(fields) c.Set(string(ContextKey_Logger), log) return log }