Files
HY2XS_flamy/apps/middleware/log.go
T

50 lines
1015 B
Go

package middleware
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"hy2xs-admin/model/constant"
"time"
)
func InitLog() {
logrus.SetOutput(&lumberjack.Logger{
Filename: constant.SystemLogPath,
MaxSize: 1,
MaxBackups: 2,
MaxAge: 30,
Compress: true,
LocalTime: true,
})
logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
logrus.SetLevel(logrus.InfoLevel)
}
func LogHandler() gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
c.Next()
statusCode := c.Writer.Status()
latencyTime := time.Since(startTime)
entry := logrus.WithFields(logrus.Fields{
"statusCode": statusCode,
"latencyTime": latencyTime.Milliseconds(),
"clientIP": c.ClientIP(),
"reqMethod": c.Request.Method,
"reqUri": c.Request.RequestURI,
})
if statusCode >= 500 {
entry.Error()
} else if statusCode >= 400 {
entry.Warn()
} else {
entry.Info()
}
}
}