You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
1.9 KiB

package Middleware
import (
"dsBaseWeb/Utils/ConfigUtil"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/tracer0tong/kafkalogrus"
"time"
)
//转为东八区时间
type CSTFormatter struct {
logrus.Formatter
}
func (u CSTFormatter) Format(e *logrus.Entry) ([]byte, error) {
e.Time = e.Time.Local()
return u.Formatter.Format(e)
}
func init() {
var err error
var hook *kafkalogrus.KafkaLogrusHook
if hook, err = kafkalogrus.NewKafkaLogrusHook(
"kh",
logrus.AllLevels,
&logrus.JSONFormatter{},
[]string{ConfigUtil.KafkaAddress},
ConfigUtil.KafkaAccessLogTopic,
true, nil); err != nil {
panic(err)
}
//设置日志格式
logrus.SetFormatter(CSTFormatter{&logrus.JSONFormatter{}})
logrus.AddHook(hook)
}
// 日志记录到 Kafka
func LoggerToKafka() gin.HandlerFunc {
return func(c *gin.Context) {
// 开始时间
startTime := time.Now().Local()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now().Local()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
//统一认证的会话id
//var identityId = -1
//var personId = -1
var deviceId = -1
/*
cookie, e := c.Request.Cookie(ConfigUtil.SessionId)
if e == nil {
deviceId, identityId, personId = SsoUtil.AnalyzeSessionId(cookie.Value)
}
*/
personId, err := c.Cookie("person_id")
if err != nil {
personId = "-1"
}
identityId, err := c.Cookie("identity_id")
if err != nil {
identityId = "-1"
}
// 日志格式
logrus.WithFields(logrus.Fields{
"status_code": statusCode,
"access_time": startTime,
"latency_time": latencyTime,
"client_ip": clientIP,
"req_method": reqMethod,
"req_uri": reqUri,
"device_id": deviceId,
"identity_id": identityId,
"person_id": personId,
}).Info()
}
}