86 lines
2.4 KiB
Go
86 lines
2.4 KiB
Go
package ginutils
|
|
|
|
import (
|
|
"time"
|
|
|
|
"git.dev.m-and-m.ovh/mderasse/gocommon/constant"
|
|
"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(constant.LogField_IP): webserver.GetClientIP(c.Request),
|
|
// Request information
|
|
string(constant.LogField_Method): c.Request.Method,
|
|
string(constant.LogField_CanonPath): c.FullPath(),
|
|
string(constant.LogField_Path): c.Request.URL.String(),
|
|
string(constant.LogField_RequestID): c.GetString(string(constant.ContextKey_RequestID)),
|
|
}
|
|
|
|
// create the logrus entry and add it to gin context
|
|
log := l.Logger.WithFields(fields)
|
|
c.Set(string(constant.ContextKey_Logger), log)
|
|
|
|
log.Info("[start]")
|
|
|
|
c.Next()
|
|
|
|
log.WithFields(
|
|
logrus.Fields{
|
|
string(constant.LogField_Duration): time.Since(start).Microseconds(),
|
|
string(constant.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(constant.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(constant.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(constant.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(constant.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(constant.ContextKey_Logger), log)
|
|
return log
|
|
}
|